List of usage examples for java.math RoundingMode HALF_UP
RoundingMode HALF_UP
To view the source code for java.math RoundingMode HALF_UP.
Click Source Link
From source file:org.yes.cart.web.support.service.impl.ShippingServiceFacadeImpl.java
/** * {@inheritDoc}/*w w w. j av a 2s. c om*/ */ public ProductPriceModel getCartShippingSupplierTotal(final ShoppingCart cart, final String supplier) { final String currency = cart.getCurrencyCode(); BigDecimal deliveriesCount = BigDecimal.ZERO; new BigDecimal(cart.getShippingList().size()); BigDecimal list = BigDecimal.ZERO; BigDecimal sale = BigDecimal.ZERO; BigDecimal taxAmount = BigDecimal.ZERO; final Set<String> taxes = new TreeSet<String>(); // sorts and de-dup's final Set<BigDecimal> rates = new TreeSet<BigDecimal>(); for (final CartItem shipping : cart.getShippingList()) { if (supplier.equals(shipping.getSupplierCode())) { deliveriesCount = deliveriesCount.add(BigDecimal.ONE); list = list.add(shipping.getListPrice().multiply(shipping.getQty()) .setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); sale = sale.add(shipping.getPrice().multiply(shipping.getQty()).setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); taxAmount = taxAmount.add(shipping.getGrossPrice().subtract(shipping.getNetPrice()) .multiply(shipping.getQty()).setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP)); if (StringUtils.isNotBlank(shipping.getTaxCode())) { taxes.add(shipping.getTaxCode()); } rates.add(shipping.getTaxRate()); } } final boolean showTax = cart.getShoppingContext().isTaxInfoEnabled(); final boolean showTaxNet = showTax && cart.getShoppingContext().isTaxInfoUseNet(); final boolean showTaxAmount = showTax && cart.getShoppingContext().isTaxInfoShowAmount(); if (showTax) { final BigDecimal costInclTax = sale; if (MoneyUtils.isFirstBiggerThanSecond(costInclTax, Total.ZERO)) { final BigDecimal totalTax = taxAmount; final BigDecimal net = costInclTax.subtract(totalTax); final BigDecimal gross = costInclTax; final BigDecimal totalAdjusted = showTaxNet ? net : gross; final BigDecimal taxRate; if (MoneyUtils.isFirstBiggerThanSecond(totalTax, Total.ZERO) && rates.size() > 1) { // mixed rates in cart we use average with round up so that tax is not reduced by rounding taxRate = totalTax.multiply(MoneyUtils.HUNDRED).divide(net, Constants.DEFAULT_SCALE, BigDecimal.ROUND_UP); } else { // single rate for all items, use it to prevent rounding errors taxRate = rates.iterator().next(); } final String tax = StringUtils.join(taxes, ','); final boolean exclusiveTax = costInclTax.compareTo(sale) > 0; if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts final MoneyUtils.Money listMoney = MoneyUtils.getMoney(list, taxRate, !exclusiveTax); final BigDecimal listAdjusted = showTaxNet ? listMoney.getNet() : listMoney.getGross(); return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, listAdjusted, totalAdjusted, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, totalAdjusted, null, showTax, showTaxNet, showTaxAmount, tax, taxRate, exclusiveTax, totalTax); } } // standard "as is" prices if (MoneyUtils.isFirstBiggerThanSecond(list, sale)) { // if we have discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, list, sale); } // no discounts return new ProductPriceModelImpl(CART_SHIPPING_TOTAL_REF, currency, deliveriesCount, sale, null); }
From source file:org.projectforge.business.fibu.datev.EmployeeSalaryExportDao.java
/** * Exports the filtered list as table with almost all fields. */// w w w . j a va 2 s . c om @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public byte[] export(final List<EmployeeSalaryDO> list) { log.info("Exporting employee salary list."); Validate.notEmpty(list); Collections.sort(list, new Comparator<EmployeeSalaryDO>() { @Override public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) { return (o1.getEmployee().getUser().getFullname()) .compareTo(o2.getEmployee().getUser().getFullname()); } }); final EmployeeFilter filter = new EmployeeFilter(); filter.setShowOnlyActiveEntries(true); filter.setDeleted(false); final List<EmployeeDO> employees = employeeDao.getList(filter); final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>(); for (final EmployeeDO employee : employees) { boolean found = false; for (final EmployeeSalaryDO salary : list) { if (salary.getEmployeeId().equals(employee.getId()) == true) { found = true; break; } } if (found == false) { missedEmployees.add(employee); } } if (CollectionUtils.isNotEmpty(missedEmployees) == true) { Collections.sort(missedEmployees, new Comparator<EmployeeDO>() { @Override public int compare(final EmployeeDO o1, final EmployeeDO o2) { return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname()); } }); } final ExportWorkbook xls = new ExportWorkbook(); final ContentProvider contentProvider = new MyContentProvider(xls); // create a default Date format and currency column xls.setContentProvider(contentProvider); final EmployeeSalaryDO first = list.get(0); final int year = first.getYear(); final int month = first.getMonth(); final DayHolder buchungsdatum = new DayHolder(); buchungsdatum.setDate(year, month, 1); final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate()); final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays(); buchungsdatum.setEndOfMonth(); final String sheetTitle = DateHelper.formatMonth(year, month); final ExportSheet sheet = xls.addSheet(sheetTitle); sheet.createFreezePane(0, 1); final ExportSheet employeeSheet = xls.addSheet(ThreadLocalUserContext.getLocalizedString("fibu.employee")); employeeSheet.setColumnWidth(0, MyXlsContentProvider.LENGTH_USER * 256); employeeSheet.setColumnWidth(1, 14 * 256); employeeSheet.setColumnWidth(2, 12 * 256); employeeSheet.setColumnWidth(3, 12 * 256); employeeSheet.setColumnWidth(4, 12 * 256); final ContentProvider provider = employeeSheet.getContentProvider(); provider.putFormat("STUNDEN", "0.00;[Red]-0.00"); final ExportRow employeeRow = employeeSheet.addRow(); employeeRow.addCell(0, ThreadLocalUserContext.getLocalizedString("fibu.employee")); employeeRow.addCell(1, ThreadLocalUserContext.getLocalizedString("fibu.employee.wochenstunden")); employeeRow.addCell(2, ThreadLocalUserContext.getLocalizedString("fibu.employee.sollstunden")); employeeRow.addCell(3, ThreadLocalUserContext.getLocalizedString("fibu.employee.iststunden")); employeeRow.addCell(4, ThreadLocalUserContext.getLocalizedString("fibu.common.difference")); // build all column names, title, widths from fixed and variable columns final int numCols = ExcelColumn.values().length; final String[] colNames = new String[numCols]; final String[] colTitles = new String[numCols]; final int[] colWidths = new int[numCols]; int idx = 0; for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) { colNames[idx] = col.name(); colTitles[idx] = ThreadLocalUserContext.getLocalizedString(col.theTitle); colWidths[idx] = col.width; ++idx; } // column property names sheet.setPropertyNames(colNames); final ContentProvider sheetProvider = sheet.getContentProvider(); sheetProvider.putFormat("STUNDEN", "0.00"); sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("KOST1", "#"); sheetProvider.putFormat("KOST2", "#"); sheetProvider.putFormat("KONTO", "#"); sheetProvider.putFormat("GEGENKONTO", "#"); sheetProvider.putFormat("DATUM", "dd.MM.yyyy"); // inform provider of column widths for (int ci = 0; ci < colWidths.length; ++ci) { sheetProvider.putColWidth(ci, colWidths[ci]); } final ExportRow headRow = sheet.addRow(); int i = 0; for (final String title : colTitles) { headRow.addCell(i++, title); } for (final EmployeeSalaryDO salary : list) { final PropertyMapping mapping = new PropertyMapping(); final PFUserDO user = getUserGroupCache().getUser(salary.getEmployee().getUserId()); Validate.isTrue(year == salary.getYear()); Validate.isTrue(month == salary.getMonth()); final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); final Kost1DO kost1 = salary.getEmployee().getKost1(); final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil(); final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration()); final Map<String, Kost2Row> rows = report.getKost2Rows(); BigDecimal sum = BigDecimal.ZERO; int j = rows.size(); for (final Kost2Row row : rows.values()) { final Kost2DO kost2 = row.getKost2(); final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId()); mapping.add(ExcelColumn.KOST1, kost1.getNummer()); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); mapping.add(ExcelColumn.KOST2, kost2.getNummer()); final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours) // mapping.add(ExcelColumn.STUNDEN, duration); mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP)); mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip()); final BigDecimal betrag; if (NumberHelper.isNotZero(netDuration) == true) { betrag = CurrencyHelper.multiply(bruttoMitAGAnteil, new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP)); } else { betrag = BigDecimal.ZERO; } sum = sum.add(betrag); if (--j == 0) { final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum); mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur)); mapping.add(ExcelColumn.KORREKTUR, korrektur); if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) { mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil); } else { mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil); } } else { mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag); mapping.add(ExcelColumn.KORREKTUR, ""); mapping.add(ExcelColumn.SUMME, ""); } mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month mapping.add(ExcelColumn.KONTO, KONTO); // constant. mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant. sheet.addRow(mapping.getMapping(), 0); } addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration); } for (final EmployeeDO employee : missedEmployees) { final PFUserDO user = getUserGroupCache().getUser(employee.getUserId()); final PropertyMapping mapping = new PropertyMapping(); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); mapping.add(ExcelColumn.SUMME, "***"); mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***"); sheet.addRow(mapping.getMapping(), 0); final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user); final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration()); addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration); } // sheet.setZoom(3, 4); // 75% final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { xls.write(baos); } catch (final IOException ex) { log.fatal("Exception encountered " + ex, ex); throw new RuntimeException(ex); } return baos.toByteArray(); }
From source file:org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.java
private BigDecimal getAvancement(SQLRowAccessor r) { Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("ECHEANCE_CLIENT")); long totalEch = 0; for (SQLRowAccessor row : rows) { if (!row.getBoolean("REGLE") && !row.getBoolean("REG_COMPTA")) { totalEch += row.getLong("MONTANT"); }/*from w w w .j a va2s .co m*/ } SQLRowAccessor avoir = r.getForeign("ID_AVOIR_CLIENT"); BigDecimal avoirTTC = BigDecimal.ZERO; if (avoir != null && !avoir.isUndefined()) { avoirTTC = new BigDecimal(avoir.getLong("MONTANT_TTC")); } final BigDecimal totalAregler = new BigDecimal(r.getLong("T_TTC")).subtract(avoirTTC); if (totalAregler.signum() > 0 && totalEch > 0) { return totalAregler.subtract(new BigDecimal(totalEch)).divide(totalAregler, MathContext.DECIMAL128) .movePointRight(2).setScale(2, RoundingMode.HALF_UP); } else { return BigDecimal.ONE.movePointRight(2); } }
From source file:net.mikaboshi.intra_mart.tools.log_stats.formatter.TemplateFileReportFormatter.java
/** * ????N?// www.ja va 2 s.c o m * @param report * @param rootMap */ private void setSessionRank(Report report, Map<String, Object> rootMap) { Map<String, Object> sessionRank = new HashMap<String, Object>(); rootMap.put("sessionRank", sessionRank); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); sessionRank.put("list", list); List<SessionReportEntry> reportList = report.getSessionReportList(); sessionRank.put("size", report.getParameter().getSessionRankSize()); sessionRank.put("total", reportList.size()); MathContext percentMathContext = new MathContext(2, RoundingMode.HALF_UP); int i = 0; for (SessionReportEntry entry : reportList) { if (++i > report.getParameter().getSessionRankSize()) { break; } Map<String, Object> row = new HashMap<String, Object>(); list.add(row); row.put("sessionId", entry.sessionId); row.put("userId", report.getUserIdFromSessionId(entry.sessionId, "")); row.put("count", entry.count); row.put("pageTimeSum", entry.pageTimeSum); row.put("pageTimeAverage", entry.pageTimeAverage); row.put("pageTimeMin", entry.pageTimeMin); row.put("pageTimeMedian", entry.pageTimeMedian); row.put("pageTime90Percent", entry.pageTime90Percent); row.put("pageTimeMax", entry.pageTimeMax); row.put("pageTimeStandardDeviation", entry.pageTimeStandardDeviation); row.put("countRate", new BigDecimal(entry.countRate * 100, percentMathContext).doubleValue()); row.put("pageTimeRate", new BigDecimal(entry.pageTimeRate * 100, percentMathContext).doubleValue()); row.put("firstAccessTime", entry.firstAccessTime); row.put("lastAccessTime", entry.lastAccessTime); } }
From source file:org.apache.carbondata.core.util.DataTypeUtil.java
private static String parseStringToBigDecimal(String value, CarbonDimension dimension) { BigDecimal bigDecimal = new BigDecimal(value).setScale(dimension.getColumnSchema().getScale(), RoundingMode.HALF_UP); BigDecimal normalizedValue = normalizeDecimalValue(bigDecimal, dimension.getColumnSchema().getPrecision()); if (null != normalizedValue) { return normalizedValue.toString(); }/* ww w. j a va 2s. c om*/ return null; }
From source file:de.langerhans.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;//from w w w . j a v a 2s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rate = o.optString(field, null); if (rate != null) { try { final double btcRate = Double .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString()); DecimalFormat df = new DecimalFormat("#.########"); df.setRoundingMode(RoundingMode.HALF_UP); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); dfs.setGroupingSeparator(','); df.setDecimalFormatSymbols(dfs); final Fiat dogeRate = Fiat.parseFiat(currencyCode, df.format(btcRate * dogeBtcConversion)); if (dogeRate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source)); break; } } catch (final NumberFormatException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:org.openvpms.archetype.rules.product.ProductPriceRules.java
/** * Calculates a product markup using the following formula: * <p/>/*w w w .j a v a 2 s. c o m*/ * {@code markup = ((price / (cost * ( 1 + tax/100))) - 1) * 100} * * @param product the product * @param cost the product cost * @param price the price * @param practice the <em>party.organisationPractice</em> used to determine product taxes * @return the markup * @throws ArchetypeServiceException for any archetype service error */ public BigDecimal getMarkup(Product product, BigDecimal cost, BigDecimal price, Party practice) { BigDecimal markup = ZERO; if (cost.compareTo(ZERO) != 0) { BigDecimal taxRate = ZERO; if (product != null) { taxRate = getTaxRate(product, practice); } markup = price.divide(cost.multiply(ONE.add(taxRate)), 3, RoundingMode.HALF_UP).subtract(ONE) .multiply(ONE_HUNDRED); if (markup.compareTo(ZERO) < 0) { markup = ZERO; } } return markup; }
From source file:org.gradoop.flink.model.impl.operators.aggregation.AggregationTest.java
@Test public void testWithMixedTypePropertyValues() throws Exception { FlinkAsciiGraphLoader loader = getLoaderFromString( "g0[" + "(va {vp=0.5});" + "(vc {vp=1});" + "(va)-[ea {ep=2L}]->(vb);" + "(vb)-[eb {ep=2.0F}]->(vc)" + "]" + "g1[" + "(va)-[ea]->(vb);" + "]" + "g2[]"); GraphCollection inputCollection = loader.getGraphCollectionByVariables("g0", "g1", "g2"); SumVertexProperty sumVertexProperty = new SumVertexProperty(VERTEX_PROPERTY); SumEdgeProperty sumEdgeProperty = new SumEdgeProperty(EDGE_PROPERTY); GraphCollection outputCollection = inputCollection.apply(new ApplyAggregation(sumVertexProperty)) .apply(new ApplyAggregation(sumEdgeProperty)); GradoopId g0Id = loader.getGraphHeadByVariable("g0").getId(); GradoopId g1Id = loader.getGraphHeadByVariable("g1").getId(); GradoopId g2Id = loader.getGraphHeadByVariable("g2").getId(); List<GraphHead> graphHeads = outputCollection.getGraphHeads().collect(); for (EPGMGraphHead graphHead : graphHeads) { assertTrue("edge sum not set", graphHead.hasProperty(sumEdgeProperty.getAggregatePropertyKey())); assertTrue("vertex sum not set", graphHead.hasProperty(sumVertexProperty.getAggregatePropertyKey())); PropertyValue vertexAggregate = graphHead.getPropertyValue(sumVertexProperty.getAggregatePropertyKey()); PropertyValue edgeAggregate = graphHead.getPropertyValue(sumEdgeProperty.getAggregatePropertyKey()); if (graphHead.getId().equals(g0Id)) { assertEquals(1.5d, vertexAggregate.getDouble(), 0.00001); assertEquals(new BigDecimal("4.0"), edgeAggregate.getBigDecimal().round(new MathContext(2, RoundingMode.HALF_UP))); } else if (graphHead.getId().equals(g1Id)) { assertEquals(0.5f, vertexAggregate.getFloat(), 0.00001); assertEquals(2L, edgeAggregate.getLong()); } else if (graphHead.getId().equals(g2Id)) { assertEquals(PropertyValue.NULL_VALUE, vertexAggregate); assertEquals(PropertyValue.NULL_VALUE, edgeAggregate); }/*from w w w. j av a 2 s. c o m*/ } }
From source file:com.bjond.utilities.MiscUtils.java
/** * Function below courtesy of: //w w w . j ava 2s . c o m * * http://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places * * * @param value value to round. * @param places places * @return the rounded double. */ public static double round(final double value, final int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); }
From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java
private void updateCSVProgress(BigDecimal totalSize) { if (taskEntity.getState().getStatus() == Status.FINISHED) { finishState();// w w w. j a v a2s .c om } else { // gets current data int readLines = fileProcessor.getNumCurrentEntry() + 1; long readBytes = fileProcessor.getReadBytes(); // calculates the current process BigDecimal readBytesBD = BigDecimal.valueOf(readBytes); double progress = readBytesBD.divide(totalSize, 4, RoundingMode.HALF_UP) .multiply(BigDecimal.valueOf(100)).doubleValue(); // updates the task state taskEntity.getState().setReadLines(readLines); taskEntity.getState().setProgress(progress); // finishes when all bytes were read if (readBytesBD.longValue() == totalSize.longValue()) { finishState(); } } }