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.efaps.esjp.accounting.transaction.evaluation.IncomingExchangeEvaluation_Base.java
/** * @param _parameter Parameter as passed by the eFaps API * @param _doc Document the calculation must be done for * @throws EFapsException on error//from ww w. ja va2 s .c o m */ @Override protected void add2Doc4Case(final Parameter _parameter, final DocumentInfo _doc) throws EFapsException { final Instance caseInst = Instance.get(_parameter.getParameterValue("case")); if (caseInst.isValid()) { _doc.setCaseInst(caseInst); final Instance periodInst = Period.evalCurrent(_parameter); final Instance periodCurrenycInstance = Period.evalCurrentCurrency(_parameter).getInstance(); final List<Instance> labelInsts = new Label().getLabelInst4Documents(_parameter, _doc.getInstance(), periodInst); final List<Account2CaseInfo> infos = Account2CaseInfo.getStandards(_parameter, caseInst); Collections.sort(infos, (_o1, _o2) -> _o1.getOrder().compareTo(_o2.getOrder())); evalAccount2CaseInfo4Relation(_parameter, _doc, infos); for (final Account2CaseInfo acc2case : infos) { boolean isDefault = acc2case.isDefault(); final boolean currencyCheck; if (acc2case.isCheckCurrency()) { currencyCheck = _doc.getRateInfo().getCurrencyInstance().equals(acc2case.getCurrencyInstance()); } else { currencyCheck = true; } if (acc2case.isCheckKey()) { if (_doc.getKey2Amount(_parameter).containsKey(acc2case.getKey())) { isDefault = true; acc2case.setAmount(DocumentInfo_Base.getAmount4Map( _doc.getKey2Amount(_parameter).get(acc2case.getKey()), acc2case.getAmountConfig(), acc2case.getAccountInstance())); } } final boolean add = (isDefault || acc2case.isClassRelation() || acc2case.isCategoryProduct() || acc2case.isTreeView()) && currencyCheck; if (add) { final BigDecimal mul = new BigDecimal(acc2case.getNumerator()).setScale(12) .divide(new BigDecimal(acc2case.getDenominator()), RoundingMode.HALF_UP); final BigDecimal amountTmp = acc2case.isClassRelation() || acc2case.isCategoryProduct() || acc2case.isCheckKey() || acc2case.isTreeView() || acc2case.isEvalRelation() ? acc2case.getAmount() : _doc.getAmount(acc2case); final BigDecimal accAmount = mul.multiply(amountTmp).setScale(2, RoundingMode.HALF_UP); RateInfo rateInfo; if (acc2case.isDeactCurrencyCheck() && !_doc.getRateInfo().getCurrencyInstance().equals(acc2case.getCurrencyInstance()) && !acc2case.getCurrencyInstance().equals(periodCurrenycInstance)) { rateInfo = new Currency().evaluateRateInfo(_parameter, _doc.getDate(), acc2case.getCurrencyInstance()); } else { rateInfo = _doc.getRateInfo(); } final BigDecimal accAmountRate = Currency.convertToCurrency(_parameter, accAmount, rateInfo, _doc.getRatePropKey(), periodCurrenycInstance); final AccountInfo account = new AccountInfo(acc2case.getAccountInstance(), accAmount); account.setRemark(acc2case.getRemark()); if (acc2case.isApplyLabel() && !labelInsts.isEmpty()) { account.setLabelInst(labelInsts.get(0)); } account.setAmountRate(accAmountRate); if (_doc.getInstance() != null) { account.setRateInfo(rateInfo, _doc.getRatePropKey()); } else { account.setRateInfo(rateInfo, getProperty(_parameter, "Type4RateInfo")); } if (acc2case.isCredit()) { account.setPostFix("_Credit"); _doc.addCredit(account); } else { account.setPostFix("_Debit"); _doc.addDebit(account); } } } } }
From source file:com.autentia.intra.manager.billing.BillManager.java
/** * Account DAO */*from ww w .ja va 2s. c o m*/ */ public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Set<ProjectRole> roles, Set<ProjectCost> costes) { List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>(); ActivityDAO activityDAO = ActivityDAO.getDefault(); ActivitySearch actSearch = new ActivitySearch(); actSearch.setBillable(new Boolean(true)); actSearch.setStartStartDate(start); actSearch.setEndStartDate(end); List<Activity> actividadesTotal = new ArrayList<Activity>(); Hashtable user_roles = new Hashtable(); for (ProjectRole proyRole : roles) { actSearch.setRole(proyRole); List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false)); actividadesTotal.addAll(actividades); } for (Activity act : actividadesTotal) { String key = act.getRole().getId().toString() + act.getUser().getId().toString(); if (!user_roles.containsKey(key)) { Hashtable value = new Hashtable(); value.put("ROLE", act.getRole()); value.put("USER", act.getUser()); user_roles.put(key, value); } } Enumeration en = user_roles.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); Hashtable pair = (Hashtable) user_roles.get(key); actSearch.setBillable(new Boolean(true)); actSearch.setStartStartDate(start); actSearch.setEndStartDate(end); ProjectRole pR = (ProjectRole) pair.get("ROLE"); User u = (User) pair.get("USER"); actSearch.setRole(pR); actSearch.setUser(u); List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch, new SortCriteria("startDate", false)); BillBreakDown brd = new BillBreakDown(); brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName()); brd.setAmount(pR.getCostPerHour()); brd.setIva(new BigDecimal(ConfigurationUtil.getDefault().getIva())); BigDecimal unitsTotal = new BigDecimal(0); for (Activity act : actividadesUsuarioRol) { BigDecimal unitsActual = new BigDecimal(act.getDuration()); unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP); unitsTotal = unitsTotal.add(unitsActual); } brd.setUnits(unitsTotal); brd.setSelected(true); desgloses.add(brd); } for (ProjectCost proyCost : costes) { BillBreakDown brd = new BillBreakDown(); brd.setConcept("Coste: " + proyCost.getName()); brd.setUnits(new BigDecimal(1)); brd.setAmount(proyCost.getCost()); brd.setIva(new BigDecimal(ConfigurationUtil.getDefault().getIva())); brd.setSelected(true); desgloses.add(brd); } return desgloses; }
From source file:com.ar.dev.tierra.api.dao.impl.FiscalDAOImpl.java
@Override public void factura_a(List<DetalleFactura> detalles, Cliente cliente) { try (PrintWriter ticket = new PrintWriter("command/factura_a.200")) { DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(1); ticket.println("b" + (char) 28 + cliente.getNombreCliente() + (char) 28 + cliente.getDocumento() + (char) 28 + cliente.getResponsabilidadIva() + (char) 28 + cliente.getTipoDocumento() + (char) 28 + cliente.getDomicilio()); ticket.println("@" + (char) 28 + "A" + (char) 28 + "T"); BigDecimal descuento = new BigDecimal(BigInteger.ZERO); for (DetalleFactura detalle : detalles) { if (detalle.getDescuentoDetalle() != null) { descuento = descuento.add(detalle.getDescuentoDetalle()); }/*www . j a va 2 s . c om*/ String price = null; BigDecimal sinIVA = detalle.getProducto().getPrecioVenta().subtract(detalle.getProducto() .getPrecioVenta().multiply(new BigDecimal(17.35)).divide(new BigDecimal(100))); price = sinIVA.setScale(4, RoundingMode.HALF_UP).toString(); ticket.println("B" + (char) 28 /*Abrimos linea*/ + detalle.getProducto().getDescripcion() + (char) 28 /*Nombre producto*/ + detalle.getCantidadDetalle() + ".0" + (char) 28 /*Cantidad*/ + price.replace(",", ".") + (char) 28 /*Precio unitario*/ + "21.0" + (char) 28 /*Impuestos IVA*/ + "M" + (char) 28 /*Suma monto*/ + "0.0" + (char) 28 /*Impuestos internos*/ + "0" + (char) 28 /*Parametro display*/ + "b"); /*Cierra de linea*/ } if (!descuento.equals(new BigDecimal(BigInteger.ZERO))) { ticket.println("T" + (char) 28 /*Abrimos linea descuento*/ + "Descuento: " + (char) 28 /*Texto a mostrar*/ + descuento + (char) 28 /*Monto descuento*/ + "m" + (char) 28 /*m: descuento, M: aumento*/ + "0" + (char) 28 /*parametro display*/ + "T"); /*cierre linea descuento*/ } ticket.println("E"); } catch (FileNotFoundException ex) { Logger.getLogger(FiscalDAOImpl.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:nl.strohalm.cyclos.utils.conversion.NumberConverter.java
private BigDecimal getDelta() { if (delta == null) { final int precision = numberFormat.getMaximumFractionDigits(); delta = BigDecimal.ONE.divide(BigDecimal.TEN.pow(precision), precision, RoundingMode.HALF_UP).negate(); }//w w w.j a va 2s. c om return delta; }
From source file:py.una.pol.karaku.math.MathContextProvider.java
private MathContextProvider() { scale = DEFAULT_SCALE; rm = RoundingMode.HALF_UP; precision = DEFAULT_PRECISION; }
From source file:org.projectforge.business.fibu.EingangsrechnungDao.java
/** * Sets the scales of percentage and currency amounts. <br/> * Gutschriftsanzeigen drfen keine Rechnungsnummer haben. Wenn eine Rechnungsnummer fr neue Rechnungen gegeben * wurde, so muss sie fortlaufend sein. Berechnet das Zahlungsziel in Tagen, wenn nicht gesetzt, damit es indiziert * wird.//from www . ja v a 2 s. c o m * * @see org.projectforge.framework.persistence.api.BaseDao#onSaveOrModify(org.projectforge.core.ExtendedBaseDO) */ @Override protected void onSaveOrModify(final EingangsrechnungDO obj) { if (obj.getZahlBetrag() != null) { obj.setZahlBetrag(obj.getZahlBetrag().setScale(2, RoundingMode.HALF_UP)); } obj.recalculate(); if (CollectionUtils.isEmpty(obj.getPositionen()) == true) { throw new UserException("fibu.rechnung.error.rechnungHatKeinePositionen"); } final int size = obj.getPositionen().size(); for (int i = size - 1; i > 0; i--) { // Don't remove first position, remove only the last empty positions. final EingangsrechnungsPositionDO position = obj.getPositionen().get(i); if (position.getId() == null && position.isEmpty() == true) { obj.getPositionen().remove(i); } else { break; } } RechnungDao.writeUiStatusToXml(obj); }
From source file:org.openhab.binding.weather.internal.bus.BindingConfigParser.java
/** * Parses the bindingConfig of an item and returns a WeatherBindingConfig. *//*from w ww.j a va 2s . c o m*/ public WeatherBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException { bindingConfig = StringUtils.trimToEmpty(bindingConfig); bindingConfig = StringUtils.removeStart(bindingConfig, "{"); bindingConfig = StringUtils.removeEnd(bindingConfig, "}"); String[] entries = bindingConfig.split("[,]"); WeatherBindingConfigHelper helper = new WeatherBindingConfigHelper(); for (String entry : entries) { String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]"); if (entryParts.length != 2) { throw new BindingConfigParseException("A bindingConfig must have a key and a value"); } String key = StringUtils.trim(entryParts[0]); String value = StringUtils.trim(entryParts[1]); value = StringUtils.removeStart(value, "\""); value = StringUtils.removeEnd(value, "\""); try { helper.getClass().getDeclaredField(key).set(helper, value); } catch (Exception e) { throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key); } } if (!helper.isValid()) { throw new BindingConfigParseException("Invalid binding: " + bindingConfig); } helper.type = StringUtils.replace(helper.type, "athmosphere", "atmosphere"); WeatherBindingConfig weatherConfig = null; if (helper.isForecast()) { Integer forecast = parseInteger(helper.forecast, bindingConfig); if (forecast < 0) { throw new BindingConfigParseException("Invalid binding, forecast must be >= 0: " + bindingConfig); } weatherConfig = new ForecastBindingConfig(helper.locationId, forecast, helper.type, helper.property); } else { weatherConfig = new WeatherBindingConfig(helper.locationId, helper.type, helper.property); } Weather validationInstance = new Weather(null); String property = weatherConfig.getWeatherProperty(); if (!Weather.isVirtualProperty(property) && !PropertyUtils.hasProperty(validationInstance, property)) { throw new BindingConfigParseException("Invalid binding, unknown type or property: " + bindingConfig); } boolean isDecimalTypeItem = item.getAcceptedDataTypes().contains(DecimalType.class); if (isDecimalTypeItem || Weather.isVirtualProperty(property)) { RoundingMode roundingMode = RoundingMode.HALF_UP; if (helper.roundingMode != null) { try { roundingMode = RoundingMode.valueOf(StringUtils.upperCase(helper.roundingMode)); } catch (IllegalArgumentException ex) { throw new BindingConfigParseException( "Invalid binding, unknown roundingMode: " + bindingConfig); } } Integer scale = 2; if (helper.scale != null) { scale = parseInteger(helper.scale, bindingConfig); if (scale < 0) { throw new BindingConfigParseException("Invalid binding, scale must be >= 0: " + bindingConfig); } } weatherConfig.setScale(roundingMode, scale); } weatherConfig.setUnit(Unit.parse(helper.unit)); if (StringUtils.isNotBlank(helper.unit) && weatherConfig.getUnit() == null) { throw new BindingConfigParseException("Invalid binding, unknown unit: " + bindingConfig); } try { if (!Weather.isVirtualProperty(property) && weatherConfig.hasUnit()) { String doubleTypeName = Double.class.getName(); String propertyTypeName = PropertyUtils.getPropertyTypeName(validationInstance, property); if (!StringUtils.equals(doubleTypeName, propertyTypeName)) { throw new BindingConfigParseException( "Invalid binding, unit specified but property is not a double type: " + bindingConfig); } } } catch (IllegalAccessException ex) { logger.error(ex.getMessage(), ex); throw new BindingConfigParseException(ex.getMessage()); } return weatherConfig; }
From source file:org.mifos.framework.components.batchjobs.helpers.BranchReportLoanArrearsAgingHelperIntegrationTest.java
@Test public void testLoanArrearsContructor() throws Exception { Money agingAmount = createMoney(TestUtils.RUPEE, 3.3333); BranchReportLoanArrearsAgingBO loanArrears = new BranchReportLoanArrearsAgingBO(null, null, null, agingAmount, createMoney(TestUtils.RUPEE, 3.3333), createMoney(TestUtils.RUPEE, 666.70)); Assert.assertEquals(/*from w w w.j a v a2s . c o m*/ agingAmount.getAmount().setScale(AccountingRules.getDigitsAfterDecimal(), RoundingMode.HALF_UP), loanArrears.getAmountAging()); }
From source file:com.sunchenbin.store.feilong.core.lang.NumberUtil.java
/** * ? {@link RoundingMode#HALF_UP},?,?.//from ww w. j ava 2s . c om * * <p style="color:red"> * ?{@link RoundingMode#HALF_UP} -2.5 ??-3, Math.round(-2.5) -2 * </p> * * @param number * number,?,?number * @return ?{@link RoundingMode#HALF_UP},?,?<br> * isNotNullOrEmpty(number)null * @see <a href="#RoundingMode">JAVA 8??</a> */ public static BigDecimal toNoScale(Serializable number) { RoundingMode roundingMode = RoundingMode.HALF_UP; return toNoScale(number, roundingMode); }
From source file:com.ehi.carshare.Main.java
private void run(String logformat, String inputFile, String outputFile) throws Exception { printAllPossibles(logformat);//from ww w . j a v a 2 s . c o m Parser<ApacheHttpLog> parser = new ApacheHttpdLoglineParser<ApacheHttpLog>(ApacheHttpLog.class, logformat); parser.ignoreMissingDissectors(); // Load file in memory File file = new File(inputFile); if (!file.exists()) { throw new RuntimeException("Input file does not exist"); } BufferedReader reader = new BufferedReader(new FileReader(file)); List<String> readLines = new ArrayList<String>(); String line = reader.readLine(); while (line != null) { readLines.add(line); line = reader.readLine(); } reader.close(); // Parse apache logs List<ApacheHttpLog> myRecords = new ArrayList<ApacheHttpLog>(); for (String readLine : readLines) { try { ApacheHttpLog myRecord = new ApacheHttpLog(); parser.parse(myRecord, readLine); if (myRecord.getAction() != null && "200".equals(myRecord.getStatus()) && myRecord.getPath() != null) { myRecords.add(myRecord); } } catch (Exception e) { /// e.printStackTrace(); } } // Group by action Map<String, List<ApacheHttpLog>> map = new HashMap<String, List<ApacheHttpLog>>(); for (ApacheHttpLog item : myRecords) { String key = item.getAction(); if (map.get(key) == null) { map.put(key, new ArrayList<ApacheHttpLog>()); } map.get(key).add(item); } // Collect stats List<ApacheHttpLogStats> recordStats = new ArrayList<ApacheHttpLogStats>(); for (Entry<String, List<ApacheHttpLog>> entry : map.entrySet()) { ApacheHttpLogStats stats = new ApacheHttpLogStats(); stats.setActionName(entry.getKey()); long responseCount = entry.getValue().size(); stats.setResponseCount(responseCount); long sum = 0; for (ApacheHttpLog myRecord : entry.getValue()) { sum = sum + myRecord.getResponseTime(); } BigDecimal average = new BigDecimal(sum) .divide(new BigDecimal(responseCount * 1000000), 2, RoundingMode.HALF_UP) .setScale(2, RoundingMode.UP); stats.setAverageResponseTime(average.toPlainString()); recordStats.add(stats); } // Write lines to file PrintWriter f0 = new PrintWriter(new FileWriter(outputFile)); f0.print(ApacheHttpLogStats.headerString()); for (ApacheHttpLogStats myRecordStats : recordStats) { f0.print(myRecordStats.toString()); } f0.close(); }