List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.openconcerto.sql.model.SQLRow.java
/** * The free order just after or before this row. * //w w w. j a v a2 s .co m * @param after whether to look before or after this row. * @return a free order, or <code>null</code> if there's no room left. */ public final BigDecimal getOrder(boolean after) { final BigDecimal destOrder = this.getOrder(); final SQLRow otherRow = this.getRow(after); final BigDecimal otherOrder; if (otherRow != null) { otherOrder = otherRow.getOrder(); } else if (after) { // dernire ligne de la table otherOrder = destOrder.add(ReOrder.DISTANCE); } else { // premire ligne otherOrder = ReOrder.MIN_ORDER; } final int decDigits = this.getTable().getOrderDecimalDigits(); final BigDecimal least = BigDecimal.ONE.scaleByPowerOfTen(-decDigits); final BigDecimal distance = destOrder.subtract(otherOrder).abs(); if (distance.compareTo(least) <= 0) return null; else { final BigDecimal mean = destOrder.add(otherOrder).divide(BigDecimal.valueOf(2)); return DecimalUtils.round(mean, decDigits); } }
From source file:org.openbravo.costing.AverageCostAdjustment.java
@Override protected BigDecimal getDefaultCostDifference(TrxType calTrxType, CostAdjustmentLine costAdjLine) { MaterialTransaction trx = costAdjLine.getInventoryTransaction(); Costing costing = getAvgCostOnMovementDate(trx, getCostDimensions(), getCostOrg(), areBackdatedTrxFixed); if (costing == null) { // In case the backdated transaction is on a date where the stock was not initialized there // isn't any costing entry related to an inventory transaction which results in a null // costing. // Try again with average algorithm getProductCost method using the movement date as // parameter. costing = AverageAlgorithm.getProductCost(trx.getMovementDate(), trx.getProduct(), getCostDimensions(), getCostOrg());//w w w .j av a 2s . c o m } if (costing != null) { BigDecimal defaultCost = costing.getCost(); Currency costCurrency = getCostCurrency(); if (costing.getCurrency() != costCurrency) { defaultCost = FinancialUtils.getConvertedAmount(costing.getCost(), costing.getCurrency(), costCurrency, trx.getTransactionProcessDate(), getCostOrg(), FinancialUtils.PRECISION_COSTING); } BigDecimal trxCalculatedCost = CostAdjustmentUtils.getTrxCost(trx, true, getCostCurrency()); defaultCost = trx.getMovementQuantity().abs().multiply(defaultCost).setScale(stdCurPrecission, RoundingMode.HALF_UP); return defaultCost.subtract(trxCalculatedCost); } return super.getDefaultCostDifference(calTrxType, costAdjLine); }
From source file:org.openvpms.web.workspace.customer.charge.CustomerChargeActItemEditor.java
/** * Updates the discount and checks that it isn't less than the total cost. * <p/>/*from w ww . ja v a 2 s . c o m*/ * If so, gives the user the opportunity to remove the discount. * * @return {@code true} if the discount was updated */ @Override protected boolean updateDiscount() { boolean updated = super.updateDiscount(); BigDecimal discount = getProperty(DISCOUNT).getBigDecimal(BigDecimal.ZERO); if (updated && discount.compareTo(BigDecimal.ZERO) != 0) { BigDecimal fixedPriceMaxDiscount = getFixedPriceMaxDiscount(null); BigDecimal unitPriceMaxDiscount = getUnitPriceMaxDiscount(null); if ((fixedPriceMaxDiscount != null && !MathRules.equals(fixedPriceMaxDiscount, ONE_HUNDRED)) || (unitPriceMaxDiscount != null && !MathRules.equals(unitPriceMaxDiscount, ONE_HUNDRED))) { // if there is a fixed and/or unit price maximum discount present, and it is not 100%, check if the // sale price is less than the cost price BigDecimal quantity = getQuantity(); BigDecimal fixedCost = getFixedCost(); BigDecimal fixedPrice = getFixedPrice(); BigDecimal unitCost = getUnitCost(); BigDecimal unitPrice = getUnitPrice(); BigDecimal costPrice = fixedCost.add(unitCost.multiply(quantity)); BigDecimal salePrice = fixedPrice.add(unitPrice.multiply(quantity)); if (costPrice.compareTo(salePrice.subtract(discount)) > 0) { ConfirmationDialog dialog = new ConfirmationDialog( Messages.get("customer.charge.discount.title"), Messages.get("customer.charge.discount.message"), ConfirmationDialog.YES_NO); dialog.addWindowPaneListener(new PopupDialogListener() { @Override public void onYes() { getProperty(DISCOUNT).setValue(BigDecimal.ZERO); super.onYes(); } }); editorQueue.queue(dialog); } } } return updated; }
From source file:org.egov.ptis.domain.service.demolition.PropertyDemolitionService.java
private Ptdemand adjustCollection(final Ptdemand oldCurrPtDmd, final Ptdemand currPtDmd, final Installment effectiveInstall) { BigDecimal totalColl = BigDecimal.ZERO; for (final EgDemandDetails oldDmdDtls : oldCurrPtDmd.getEgDemandDetails()) if (oldDmdDtls.getInstallmentStartDate().equals(effectiveInstall.getFromDate()) || oldDmdDtls.getInstallmentStartDate().after(effectiveInstall.getFromDate())) totalColl = totalColl.add(oldDmdDtls.getAmtCollected()); if (totalColl.compareTo(BigDecimal.ZERO) > 0) { for (final EgDemandDetails dmdDtls : currPtDmd.getEgDemandDetails()) if (dmdDtls.getInstallmentStartDate().equals(effectiveInstall.getFromDate()) || dmdDtls.getInstallmentStartDate().after(effectiveInstall.getFromDate())) if (dmdDtls.getAmount().compareTo(totalColl) >= 0) { dmdDtls.setAmtCollected(totalColl); totalColl = BigDecimal.ZERO; } else { dmdDtls.setAmtCollected(dmdDtls.getAmount()); totalColl = totalColl.subtract(dmdDtls.getAmount()); }//from ww w . j a v a2 s . c o m if (totalColl.compareTo(BigDecimal.ZERO) > 0) { EgDemandDetails newDtls; final Map<String, Installment> yearwiseInstMap = propertyTaxUtil .getInstallmentsForCurrYear(new Date()); final Installment installment = yearwiseInstMap.get(CURRENTYEAR_SECOND_HALF); newDtls = ptBillServiceImpl.insertDemandDetails(ADVANCE_DMD_RSN_CODE, totalColl, installment); currPtDmd.addEgDemandDetails(newDtls); } } return currPtDmd; }
From source file:org.egov.works.services.AbstractEstimateService.java
private void persistDepositCodeAppDetails(final DepositWorksUsage depositWorksUsage) { AbstractEstimateAppropriation estimateAppropriation = null; final int finYearId = financialYearHibernateDAO.getFinYearByDate(new Date()).getId().intValue(); final BigDecimal creditBalance = depositWorksUsage.getTotalDepositAmount(); final AbstractEstimate abstractEstimate = depositWorksUsage.getAbstractEstimate(); BigDecimal utilizedAmt = depositWorksUsageService.getTotalUtilizedAmountForDepositWorks( abstractEstimate.getFinancialDetails().get(0), depositWorksUsage.getCreatedDate()); BigDecimal balance = BigDecimal.ZERO; if (utilizedAmt == null) { balance = creditBalance;//from ww w . ja v a 2s . c om utilizedAmt = BigDecimal.ZERO; } else balance = creditBalance.subtract(utilizedAmt); estimateAppropriation = estimateAppropriationService .findByNamedQuery("getDepositWorksUsageForEstimateByFinYear", abstractEstimate.getId(), finYearId); if (estimateAppropriation != null) { estimateAppropriation.setBalanceAvailable(balance); estimateAppropriation.setDepositWorksUsage(depositWorksUsage); } else { estimateAppropriation = new AbstractEstimateAppropriation(); estimateAppropriation.setAbstractEstimate(abstractEstimate); estimateAppropriation.setBalanceAvailable(balance); estimateAppropriation.setDepositWorksUsage(depositWorksUsage); } estimateAppropriationService.persist(estimateAppropriation); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The Gamma function.//from w ww. j a v a 2 s . c o m * * @param x The argument. * @return Gamma(x). */ static public BigDecimal Gamma(final BigDecimal x) { /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33 */ if (x.compareTo(BigDecimal.ZERO) < 0) { return divideRound(Gamma(x.add(BigDecimal.ONE)), x); } else if (x.doubleValue() > 1.5) { /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n). */ int n = (int) (x.doubleValue() - 0.5); BigDecimal xmin1 = x.subtract(new BigDecimal(n)); return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n)); } else { /* apply Abramowitz-Stegun 6.1.33 */ BigDecimal z = x.subtract(BigDecimal.ONE); /* add intermediately 2 digits to the partial sum accumulation */ z = scalePrec(z, 2); MathContext mcloc = new MathContext(z.precision()); /* measure of the absolute error is the relative error in the first, logarithmic term */ double eps = x.ulp().doubleValue() / x.doubleValue(); BigDecimal resul = log(scalePrec(x, 2)).negate(); if (x.compareTo(BigDecimal.ONE) != 0) { BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc)); resul = resul.add(multiplyRound(z, gammCompl)); for (int n = 2;; n++) { /* multiplying z^n/n by zeta(n-1) means that the two relative errors add. * so the requirement in the relative error of zeta(n)-1 is that this is somewhat * smaller than the relative error in z^n/n (the absolute error of thelatter is the * absolute error in z) */ BigDecimal c = divideRound(z.pow(n, mcloc), n); MathContext m = new MathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue())); c = c.round(m); /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n. * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10. * Error from 1/2^n is c*err(sigma-1). * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is * of the order of 1. */ if (eps / 100. / c.doubleValue() < 0.01) { m = new MathContext(err2prec(eps / 100. / c.doubleValue())); } else { m = new MathContext(2); } /* zeta(n) -1 */ BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE); c = multiplyRound(c, zetm1); if (n % 2 == 0) { resul = resul.add(c); } else { resul = resul.subtract(c); } /* alternating sum, so truncating as eps is reached suffices */ if (Math.abs(c.doubleValue()) < eps) { break; } } } /* The relative error in the result is the absolute error in the * input variable times the digamma (psi) value at that point. */ double psi = 0.5772156649; double zdbl = z.doubleValue(); for (int n = 1; n < 5; n++) { psi += zdbl / n / (n + zdbl); } eps = psi * x.ulp().doubleValue() / 2.; mcloc = new MathContext(err2prec(eps)); return exp(resul).round(mcloc); } }
From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java
@Override public BigDecimal calculateAmount(final AccountFeeLog feeLog, final Member member) { AccountFee fee = feeLog.getAccountFee(); if (!fee.getGroups().contains(member.getGroup())) { // The member is not affected by this fee log return null; }/* ww w. java 2 s. co m*/ final Period period = feeLog.getPeriod(); final MemberAccountType accountType = fee.getAccountType(); final ChargeMode chargeMode = fee.getChargeMode(); final BigDecimal freeBase = fee.getFreeBase(); // Calculate the charge amount BigDecimal chargedAmount = BigDecimal.ZERO; BigDecimal amount = BigDecimal.ZERO; Calendar endDate = (period != null) ? period.getEnd() : null; final AccountDateDTO balanceParams = new AccountDateDTO(member, accountType, endDate); if (chargeMode.isFixed()) { boolean charge = true; if (freeBase != null) { final BigDecimal balance = accountService.getBalance(balanceParams); if (balance.compareTo(freeBase) <= 0) { charge = false; } } // Fixed fee amount if (charge) { amount = feeLog.getAmount(); } } else if (chargeMode.isBalance()) { // Percentage over balance final boolean positiveBalance = !chargeMode.isNegative(); BigDecimal balance = accountService.getBalance(balanceParams); // Skip if balance is out of range boolean charge = true; // Apply the free base if (freeBase != null) { if (positiveBalance) { balance = balance.subtract(freeBase); } else { balance = balance.add(freeBase); } } // Check if something will be charged if ((positiveBalance && balance.compareTo(BigDecimal.ZERO) <= 0) || (!positiveBalance && balance.compareTo(BigDecimal.ZERO) >= 0)) { charge = false; } if (charge) { // Get the charged amount chargedAmount = feeLog.getAmountValue().apply(balance.abs()); amount = settingsService.getLocalSettings().round(chargedAmount); } } else if (chargeMode.isVolume()) { // Percentage over average transactioned volume amount = calculateChargeOverTransactionedVolume(feeLog, member); } // Ensure the amount is valid final BigDecimal minPayment = paymentService.getMinimumPayment(); if (amount.compareTo(minPayment) < 0) { amount = BigDecimal.ZERO; } return amount; }
From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java
public int numberOfDecimals(BigDecimal value) { if (value == null) { return -1; }/*from w w w . ja v a 2s . c o m*/ int i = value.subtract(value.setScale(0, RoundingMode.FLOOR)).movePointRight(value.scale()).intValue(); return Integer.toString(i).length(); }
From source file:service.AdService.java
public void create(Boolean isAutherized, Long catId, String email, String phone, String price, MultipartFile previews[], String name, String desc, Long booleanIds[], String booleanVals[], Long stringIds[], String stringVals[], Long numIds[], String snumVals[], Long dateIds[], Date dateVals[], Long selIds[], Long selVals[], Long multyIds[], String multyVals[], Date dateFrom, Date dateTo, Long localIds[]) throws IOException { Boolean newUser = false;//from w ww. j ava2 s . c o m if (catId != null) { Category cat = catDao.find(catId); if (cat != null) { if (isAutherized || (!isAutherized && email != null && !email.equals(""))) { PhoneEditor phe = new PhoneEditor(); phone = phe.getPhone(phone); addError(phe.error); if ((phone == null || phone.equals("")) && (email == null || email.equals(""))) { addError( " email ? "); } User user = userService.getUserByMail(email); if (!isAutherized && user == null) { user = userService.registerStandardUser(email); newUser = true; List<String> userErrors = userService.getErrors(); if (!userErrors.isEmpty()) { for (String er : userErrors) { addError("user_service: " + er + "; "); } } } Ad ad = new Ad(); ad.setInsertDate(new Date()); ad.setShowCount((long) 0); ad.setStatus(Ad.NEW); ad.setDateFrom(dateFrom); ad.setDateTo(dateTo); ad.setEmail(email); ad.setPhone(phone); ad.setAuthor(user); ad.setCat(cat); Set<Locality> locals = new HashSet(); /*if (region != null) { if (region.isAllRussia()) { locals.addAll(locDao.getAll()); } else { locals.addAll(region.getLocalities()); } }*/ if (localIds != null && localIds.length > 0) { locals.addAll(locDao.getLocs(localIds)); } else { addError(" ? "); } ad.setLocalities(locals); ad.setName(name); ad.setDescription(desc); ad.setPrice(getNumFromString(price, true)); ad.setValues(new HashSet()); if (validate(ad) && getErrors().isEmpty()) { adDao.save(ad); List<Long> reqParamIds = catDao.getRequiredParamsIds(catId); List<Parametr> catParams = paramDao.getParamsFromCat(catId); int i = 0; ArrayList<String> paramValsErrs = new ArrayList(); // ? ?? ? ? ? ??, ?, ? ? //? ad ArrayList<ParametrValue> list4Save = new ArrayList(); // if (booleanIds != null) { if (booleanVals == null) { booleanVals = new String[booleanIds.length]; } while (i < booleanIds.length) { Parametr p = paramDao.find(booleanIds[i]); if (catParams.contains(p) && Parametr.BOOL == p.getParamType()) { Long val = ParametrValue.NO; String sval = ""; if (booleanVals[i] != null) { val = ParametrValue.YES; sval = ""; } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setSelectVal(val); pv.setStringVal(sval); if (validate(pv)) { list4Save.add(pv); } } i++; } } if (stringVals != null && stringVals.length > 0) { i = 0; while (i < stringIds.length) { Long paramId = stringIds[i]; Parametr p = paramDao.find(paramId); if (catParams.contains(p) && Parametr.TEXT == p.getParamType()) { String val = stringVals[i]; if (val != null && !val.equals("")) { if (reqParamIds.contains(paramId)) { reqParamIds.remove(paramId); } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setStringVal(val); if (validate(pv)) { list4Save.add(pv); } } } i++; } } if (snumVals != null && snumVals.length > 0) { i = 0; while (i < numIds.length) { Long paramId = numIds[i]; Parametr p = paramDao.find(paramId); if (catParams.contains(p) && Parametr.NUM == p.getParamType()) { String sval = snumVals[i]; if (sval != null && !sval.equals("")) { Double val = getNumFromString(sval, true); if (reqParamIds.contains(paramId)) { reqParamIds.remove(paramId); } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setNumVal(val); pv.setStringVal(StringAdapter.getString(val)); if (validate(pv)) { list4Save.add(pv); } } } i++; } if (!getErrors().isEmpty()) { for (String e : getErrors()) { paramValsErrs.add(e); } } } if (dateVals != null && dateVals.length > 0) { i = 0; while (i < dateIds.length) { Long paramId = dateIds[i]; Parametr p = paramDao.find(paramId); if (catParams.contains(p) && Parametr.DATE == p.getParamType()) { Date val = dateVals[i]; if (val != null) { if (reqParamIds.contains(paramId)) { reqParamIds.remove(paramId); } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setDateVal(val); pv.setStringVal(DateAdapter.formatByDate(val, DateAdapter.SMALL_FORMAT)); if (validate(pv)) { list4Save.add(pv); } } } i++; } } if (selVals != null && selVals.length > 0) { i = 0; while (i < selIds.length) { Long paramId = selIds[i]; Parametr p = paramDao.find(paramId); if (catParams.contains(p) && Parametr.SELECTING == p.getParamType()) { Long val = selVals[i]; if (val != null && !val.equals(0L)) { if (reqParamIds.contains(paramId)) { reqParamIds.remove(paramId); } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setSelectVal(val); pv.setStringVal(paramSelDao.find(val).getName()); if (validate(pv)) { list4Save.add(pv); } } } i++; } } //? ? //TO DO (??) if (multyVals != null && multyVals.length > 0) { for (String rawVal : multyVals) { String idValArr[] = rawVal.split("_"); if (idValArr.length == 2) { String strId = idValArr[0]; String strVal = idValArr[1]; Long paramId = Long.valueOf(strId); Long val = Long.valueOf(strVal); Parametr p = paramDao.find(paramId); if (catParams.contains(p) && Parametr.MULTISELECTING == p.getParamType()) { if (reqParamIds.contains(paramId) && val != null) { reqParamIds.remove(paramId); } ParametrValue pv = new ParametrValue(); pv.setAd(ad); pv.setParametr(p); pv.setSelectVal(val); pv.setStringVal(paramSelDao.find(val).getName()); if (validate(pv)) { list4Save.add(pv); } } } } } //? ? ? ? if (!reqParamIds.isEmpty() || !paramValsErrs.isEmpty()) { for (Long id : reqParamIds) { addError(" " + paramDao.find(id).getName() + "; "); } //? adDao.delete(ad); } else { for (ParametrValue pv : list4Save) { paramValueDao.save(pv); } File file = new File("/usr/local/seller/preview/" + ad.getId() + "/"); if (file.exists()) { for (File f : file.listFiles()) { f.delete(); } file.delete(); } file.mkdirs(); if (previews != null && previews.length > 0) { i = 0; while (i < 10 && i < previews.length) { MultipartFile prev = previews[i]; if (prev != null && 0L < prev.getSize()) { if (prev.getSize() <= (long) 3 * 1024 * 1024) { File f = new File( "/usr/local/seller/preview/" + ad.getId() + "/supPreview"); if (f.exists()) { f.delete(); } prev.transferTo(f); //to do ? - ?? try { BufferedImage bi = ImageIO.read(f); BigDecimal x = BigDecimal.valueOf(0); BigDecimal y = BigDecimal.valueOf(0); BigDecimal h = BigDecimal.valueOf(bi.getHeight()); BigDecimal w = BigDecimal.valueOf(bi.getWidth()); if (h.compareTo(w) > 0) { y = (h.subtract(w)).divide(BigDecimal.valueOf(2), RoundingMode.HALF_UP); h = w; } else if (h.compareTo(w) < 0) { x = (w.subtract(h)).divide(BigDecimal.valueOf(2), RoundingMode.HALF_UP); w = h; } bi = bi.getSubimage(x.intValue(), y.intValue(), w.intValue(), h.intValue()); f.delete(); f = new File("/usr/local/seller/preview/" + ad.getId() + "/" + i); ImageIO.write(bi, "png", f); } catch (Exception e) { addError( "? ? " + prev.getName() + /*"; s="+prev.getSize()+"; t="+prev.getContentType()+"; l="+previews.length+*/ "; " + StringAdapter.getStackTraceException(e)); } } else { addError(" " + prev.getName() + " , ? 3 ."); } } i++; } } if (newUser) { userService.notifyAboutRegistration(email); } } } /* else { addError("user:" + user.getId() + " " + user.getName()); }*/ } else { addError( "? ?? email"); } } else { addError("? ? " + catId + " ."); } } else { addError("? "); } }
From source file:org.egov.ptis.domain.service.transfer.PropertyTransferService.java
/** * API to calculate mutation fee//from w w w.j av a2s . com * * @param partyValue * @param departmentValue * @return MutationFee */ public BigDecimal calculateMutationFee(final BigDecimal partyValue, final BigDecimal departmentValue) { BigDecimal mutationFee = BigDecimal.ZERO; BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue; if (documentValue.compareTo(BigDecimal.ZERO) > 0) { List<MutationFeeDetails> mutationFeeDetailsList = mutationFeeRepository.getMutationFee(documentValue); if (!mutationFeeDetailsList.isEmpty()) { MutationFeeDetails mutationFeeDetails = mutationFeeDetailsList.get(0); if (mutationFeeDetails != null) { if (mutationFeeDetails.getFlatAmount() != null && mutationFeeDetails.getFlatAmount().compareTo(BigDecimal.ZERO) > 0) if ("N".equalsIgnoreCase(mutationFeeDetails.getIsRecursive().toString())) mutationFee = mutationFeeDetails.getFlatAmount(); else { BigDecimal excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit()) .add(BigDecimal.ONE); BigDecimal multiplicationFactor = excessDocValue .divide(mutationFeeDetails.getRecursiveFactor(), BigDecimal.ROUND_CEILING); mutationFee = mutationFeeDetails.getFlatAmount() .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveAmount())); } if (mutationFeeDetails.getPercentage() != null && mutationFeeDetails.getPercentage().compareTo(BigDecimal.ZERO) > 0 && mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase("N")) mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage()) .divide(PropertyTaxConstants.BIGDECIMAL_100); } } } return mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP); }