List of usage examples for java.math BigDecimal multiply
public BigDecimal multiply(BigDecimal multiplicand)
(this × multiplicand)
, and whose scale is (this.scale() + multiplicand.scale()) . From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
public <T extends PurApAccountingLine> void updateAccountAmountsWithTotal2(List<T> sourceAccountingLines, KualiDecimal totalAmount) {/*from w ww . ja v a 2s . c om*/ if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) { KualiDecimal accountTotal = KualiDecimal.ZERO; T lastAccount = null; for (T account : sourceAccountingLines) { if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { // OlePaymentRequestItem item = new OlePaymentRequestItem(); BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()) .divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString())) .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR))); } else { account.setAmount(KualiDecimal.ZERO); } accountTotal = accountTotal.add(account.getAmount()); lastAccount = account; } // put excess on last account if (lastAccount != null) { KualiDecimal difference = totalAmount.subtract(accountTotal); lastAccount.setAmount(lastAccount.getAmount().add(difference)); } } else { // zero out if extended price is zero for (T account : sourceAccountingLines) { account.setAmount(KualiDecimal.ZERO); } } }
From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
/** * calculates values for a list of accounting lines based on an amount * * @param sourceAccountingLines/*from ww w . ja v a 2s. c o m*/ * @param totalAmount */ public <T extends PurApAccountingLine> void updateAccountAmountsWithTotalForAdditionalCharge( List<T> sourceAccountingLines, KualiDecimal totalAmount) { if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) { KualiDecimal accountTotal = KualiDecimal.ZERO; T lastAccount = null; for (T account : sourceAccountingLines) { if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()) .divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString())) .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR))); } else { account.setAmount(KualiDecimal.ZERO); } accountTotal = accountTotal.add(account.getAmount()); lastAccount = account; } // put excess on last account if (lastAccount != null) { KualiDecimal difference = totalAmount.subtract(accountTotal); lastAccount.setAmount(lastAccount.getAmount().add(difference)); } } else { // zero out if extended price is zero for (T account : sourceAccountingLines) { account.setAmount(KualiDecimal.ZERO); } } }
From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java
@Deprecated public static String getConvertedAmt(String Amt, String CurFrom_ID, String CurTo_ID, String ConvDate, String RateType, String client, String org, String recordId, String docType, ConnectionProvider conn) { boolean useSystemConversionRate = true; if (log4j.isDebugEnabled()) log4j.debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: " + ConvDate + " - RateType:" + RateType + " - client:" + client + "- org:" + org); if (Amt.equals("")) throw new IllegalArgumentException("AcctServer - getConvertedAmt - required parameter missing - Amt"); if ((CurFrom_ID.equals(CurTo_ID) && !docType.equals(EXCHANGE_DOCTYPE_Transaction)) || Amt.equals("0")) return Amt; AcctServerData[] data = null;/*from w w w. j a v a 2 s. co m*/ OBContext.setAdminMode(); try { if (ConvDate != null && ConvDate.equals("")) ConvDate = DateTimeData.today(conn); // ConvDate IN DATE if (RateType == null || RateType.equals("")) RateType = "S"; data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType, client, org); // Search if exists any conversion rate at document level OBCriteria<ConversionRateDoc> docRateCriteria = OBDal.getInstance() .createCriteria(ConversionRateDoc.class); if (docType.equals(EXCHANGE_DOCTYPE_Invoice) && recordId != null) { docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, OBDal.getInstance().get(Currency.class, CurTo_ID))); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, OBDal.getInstance().get(Currency.class, CurFrom_ID))); // get reversed invoice id if exist. OBCriteria<ReversedInvoice> reversedCriteria = OBDal.getInstance() .createCriteria(ReversedInvoice.class); reversedCriteria.add(Restrictions.eq(ReversedInvoice.PROPERTY_INVOICE, OBDal.getInstance().get(Invoice.class, recordId))); if (!reversedCriteria.list().isEmpty()) { String strDateFormat; strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("dateFormat.java"); final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat); ConvDate = dateFormat .format(reversedCriteria.list().get(0).getReversedInvoice().getAccountingDate()); data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType, client, org); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE, OBDal.getInstance() .get(Invoice.class, reversedCriteria.list().get(0).getReversedInvoice().getId()))); } else { docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE, OBDal.getInstance().get(Invoice.class, recordId))); } useSystemConversionRate = false; } else if (docType.equals(EXCHANGE_DOCTYPE_Payment)) { docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, OBDal.getInstance().get(Currency.class, CurTo_ID))); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, OBDal.getInstance().get(Currency.class, CurFrom_ID))); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_PAYMENT, OBDal.getInstance().get(FIN_Payment.class, recordId))); useSystemConversionRate = false; } else if (docType.equals(EXCHANGE_DOCTYPE_Transaction)) { APRM_FinaccTransactionV a = OBDal.getInstance().get(APRM_FinaccTransactionV.class, recordId); if (a.getForeignCurrency() != null) { // && !a.getForeignCurrency().getId().equals(CurTo_ID) String strDateFormat; strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("dateFormat.java"); final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat); Amt = a.getForeignAmount().toString(); data = AcctServerData.currencyConvert(conn, Amt, a.getForeignCurrency().getId(), CurTo_ID, ConvDate, RateType, client, org); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, OBDal.getInstance().get(Currency.class, CurTo_ID))); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, OBDal.getInstance().get(Currency.class, a.getForeignCurrency().getId()))); } else { docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, OBDal.getInstance().get(Currency.class, CurTo_ID))); docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, OBDal.getInstance().get(Currency.class, CurFrom_ID))); } docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_FINANCIALACCOUNTTRANSACTION, OBDal.getInstance().get(APRM_FinaccTransactionV.class, recordId))); useSystemConversionRate = false; } if (docType.equals(EXCHANGE_DOCTYPE_Invoice) || docType.equals(EXCHANGE_DOCTYPE_Payment) || docType.equals(EXCHANGE_DOCTYPE_Transaction)) { List<ConversionRateDoc> conversionRates = docRateCriteria.list(); if (!conversionRates.isEmpty() && !useSystemConversionRate) { BigDecimal Amount = new BigDecimal(Amt); BigDecimal AmountConverted = Amount.multiply(conversionRates.get(0).getRate()).setScale(2, BigDecimal.ROUND_HALF_UP); return AmountConverted.toString(); } } } catch (ServletException e) { log4j.warn(e); e.printStackTrace(); } finally { OBContext.restorePreviousMode(); } if (data == null || data.length == 0) { /* * log4j.error("No conversion ratio"); throw new * ServletException("No conversion ratio defined!"); */ return ""; } else { if (log4j.isDebugEnabled()) log4j.debug("getConvertedAmount - converted:" + data[0].converted); return data[0].converted; } }
From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java
/** * calculates values for a list of accounting lines based on an amount for proportional method * * @param sourceAccountingLines/*from w ww . j a v a 2s . c o m*/ * @param totalAmount */ @Override public <T extends PurApAccountingLine> void updatePreqProporationalAccountAmountsWithTotal( List<T> sourceAccountingLines, KualiDecimal totalAmount) { if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) { KualiDecimal accountTotal = KualiDecimal.ZERO; BigDecimal accountTotalPercent = BigDecimal.ZERO; T lastAccount = null; for (T account : sourceAccountingLines) { if (ObjectUtils.isNotNull(account.getAccountLinePercent()) || ObjectUtils.isNotNull(account.getAmount())) { if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()) .divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString())) .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR))); } } if (ObjectUtils.isNotNull(account.getAmount())) { accountTotal = accountTotal.add(account.getAmount()); } if (ObjectUtils.isNotNull(account.getAccountLinePercent())) { accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent()); } lastAccount = account; } // put excess on last account if (lastAccount != null) { KualiDecimal difference = totalAmount.subtract(accountTotal); if (ObjectUtils.isNotNull(lastAccount.getAmount())) { lastAccount.setAmount(lastAccount.getAmount().add(difference)); } BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent) .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING); if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) { lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference)); } } } }
From source file:org.egov.ptis.actions.common.AjaxCommonAction.java
/** * API to calculate Mutation Fee dynamically * * @return/* ww w . j av a 2 s .c o m*/ */ @Action(value = "/ajaxCommon-calculateMutationFee") public String calculateMutationFee() { // Maximum among partyValue and departmentValue will be considered as // the documentValue final BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue; if (documentValue.compareTo(ZERO) > 0) { BigDecimal excessDocValue; BigDecimal multiplicationFactor; final MutationFeeDetails mutationFeeDetails = (MutationFeeDetails) getPersistenceService().find( "from MutationFeeDetails where lowLimit <= ? and (highLimit is null OR highLimit >= ?) and toDate > now()", documentValue, documentValue); if (mutationFeeDetails != null) { if (mutationFeeDetails.getFlatAmount() != null && mutationFeeDetails.getFlatAmount().compareTo(ZERO) > 0) if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N)) mutationFee = mutationFeeDetails.getFlatAmount(); else { excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit()) .add(BigDecimal.ONE); multiplicationFactor = excessDocValue.divide(mutationFeeDetails.getRecursiveAmount(), BigDecimal.ROUND_CEILING); mutationFee = mutationFeeDetails.getFlatAmount() .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveFactor())); } if (mutationFeeDetails.getPercentage() != null && mutationFeeDetails.getPercentage().compareTo(ZERO) > 0) if (mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase(RECURSIVEFACTOR_N)) mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage()) .divide(PropertyTaxConstants.BIGDECIMAL_100); mutationFee = mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP); } } return RESULT_MUTATION_FEE; }
From source file:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java
/** * Extra precise sqrt function for use with BigDecimal class. Uses Newton's * method to roughly double the number of significant digits of typical * floating-point sqrt function. (This gem was found on StackOverflow.com) * * @param value/*w w w. ja va 2 s. c om*/ * @param mc * @return square root of {@code value} */ public static final BigDecimal sqrt(BigDecimal value, MathContext mc) { BigDecimal x = new BigDecimal(Math.sqrt(value.doubleValue()), mc); return x.add(new BigDecimal(value.subtract(x.multiply(x)).doubleValue() / (x.doubleValue() * 2.0), mc)); }
From source file:org.kuali.coeus.common.budget.impl.personnel.BudgetPersonnelBudgetServiceImpl.java
public List<BudgetPersonSalaryDetails> calculatePersonSalary(Budget budget, int personIndex) { List<BudgetPersonSalaryDetails> budgetPersonSalaryDetails = new ArrayList<BudgetPersonSalaryDetails>(); String rate = getParameterService().getParameterValueAsString(ProposalDevelopmentDocument.class, Constants.DEFAULT_INFLATION_RATE_FOR_SALARY); List<BudgetPeriod> budgetPeriodList = null; BigDecimal actualPersonSalary = ScaleTwoDecimal.ZERO.bigDecimalValue(); BigDecimal personSalary = ScaleTwoDecimal.ZERO.bigDecimalValue(); BigDecimal newRate = new ScaleTwoDecimal(rate).bigDecimalValue(); budgetPeriodList = budget.getBudgetPeriods(); BudgetPerson budgetPerson = budget.getBudgetPerson(personIndex); for (BudgetPeriod budgetPeriodData : budgetPeriodList) { BudgetPersonSalaryDetails personSalaryDetails = new BudgetPersonSalaryDetails(); personSalaryDetails.setBudgetPerson(budgetPerson); personSalaryDetails.setBudgetId(budget.getBudgetId()); personSalaryDetails.setPersonSequenceNumber(budgetPerson.getPersonSequenceNumber()); personSalaryDetails.setBudgetPeriod(budgetPeriodData.getBudgetPeriod()); personSalaryDetails.setPersonId(budgetPerson.getPersonId()); if (budgetPeriodData.getBudgetPeriod() == BUDGET_PERIOD_1) { if (budgetPerson.getEffectiveDate().equals(budgetPerson.getStartDate())) { personSalaryDetails.setBaseSalary(budgetPerson.getCalculationBase()); actualPersonSalary = budgetPerson.getCalculationBase().bigDecimalValue(); } else { actualPersonSalary = budgetPerson .getCalculationBase().add(new ScaleTwoDecimal(budgetPerson.getCalculationBase() .bigDecimalValue().multiply(newRate.divide( new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP)))) .bigDecimalValue(); }/*w w w . j a v a2 s. c o m*/ } else { personSalary = actualPersonSalary.add(actualPersonSalary.multiply( newRate.divide(new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP))); personSalaryDetails.setBaseSalary(new ScaleTwoDecimal(personSalary)); actualPersonSalary = personSalary; } budgetPersonSalaryDetails.add(personSalaryDetails); } return budgetPersonSalaryDetails; }
From source file:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java
/** * Computes real roots for quadratic equation of the form * {@code ax^2 + bx + c = 0}, given real coefficients {@code a}, {@code b}, * and {@code c}. If there are two distinct roots, they are returned in a * two-element array. If there is a single root or two identical roots, the * result is returned in a single-element array. If there are no real-valued * roots, the function returns a zero-length array. Note that the * discriminant {@code b*b-4*a*c} contains the potential for catastrophic * cancellation if its two terms are nearly equal, so in this case the * algorithm uses {@code BigDecimal}s and methods described by W. Kahan in * "On the Cost of Floating-Point Computation Without Extra-Precise * Arithmetic"/*from w w w . j av a 2s. co m*/ * (<a href="http://www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf">www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf/</a>), * which references TJ Dekker (A Floating-Point Technique for Extending the * Available Precision,? pp 234-242 in Numerische Mathematik 18, 1971). * * @param a quadratic coefficient * @param b linear coefficient * @param c constant term * @return array of distinct roots in order from least to greatest, or * zero-length array if there are no real-valued roots */ public static final double[] quadraticRoots(double a, double b, double c) { if (a == 0.0) { if (b == 0.0) { return new double[0]; } else { return new double[] { -c / b }; } } else if (b == 0.0) { if (c == 0.0) { return new double[] { 0.0 }; } else { double q = Math.sqrt(-c / a); return new double[] { -q, q }; } } else if (c == 0.0) { if (a == 0.0) { return new double[] { 0.0 }; } else { double r = -b / a; if (r < 0.0) { return new double[] { r, 0.0 }; } else { return new double[] { 0.0, r }; } } } else { double p = b * b; double q = 4.0 * a * c; double d = p - q; double sqrtD = Math.sqrt(d); double pie = 3; // see reference cited in javadoc for the origin of this number if (pie * Math.abs(d) < p + q) { BigDecimal aBD = new BigDecimal(a, MathContext.DECIMAL64); BigDecimal bBD = new BigDecimal(b, MathContext.DECIMAL64); BigDecimal cBD = new BigDecimal(c, MathContext.DECIMAL64); BigDecimal pBD = bBD.multiply(bBD); BigDecimal qBD = aBD.multiply(cBD).multiply(new BigDecimal(4, MathContext.DECIMAL64)); BigDecimal dBD = pBD.subtract(qBD); if (dBD.doubleValue() < 0) { // discriminant < 0.0 return new double[0]; } else if (dBD.doubleValue() == 0) { // discriminant is truly zero to double precision return new double[] { -b / (2.0 * a) }; } sqrtD = sqrt(dBD, MathContext.DECIMAL64).doubleValue(); } double s = -0.5 * (b + Math.signum(b) * sqrtD); double r1 = s / a; double r2 = c / s; if (r1 < r2) { return new double[] { r1, r2 }; } else if (r1 > r2) { return new double[] { r2, r1 }; } else { return new double[] { r1 }; } } }
From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java
@Override public LoanRepaymentAmountsDTO getLoanPaymentAmount(final LoanPaymentDTO dto) { final LoanRepaymentAmountsDTO ret = new LoanRepaymentAmountsDTO(); Calendar date = dto.getDate(); if (date == null) { date = Calendar.getInstance(); }//w ww . j av a 2 s . c o m final Loan loan = fetchService.fetch(dto.getLoan(), Loan.Relationships.TRANSFER, Loan.Relationships.PAYMENTS); LoanPayment payment = fetchService.fetch(dto.getLoanPayment()); if (payment == null) { payment = loan.getFirstOpenPayment(); } ret.setLoanPayment(payment); // Update the dto with fetched values dto.setLoan(loan); dto.setLoanPayment(payment); if (payment != null) { payment = fetchService.fetch(payment, LoanPayment.Relationships.TRANSFERS); final BigDecimal paymentAmount = payment.getAmount(); BigDecimal remainingAmount = paymentAmount; Calendar expirationDate = payment.getExpirationDate(); Calendar lastPaymentDate = (Calendar) expirationDate.clone(); expirationDate = DateUtils.truncate(expirationDate, Calendar.DATE); final LoanParameters parameters = loan.getParameters(); Collection<Transfer> transfers = payment.getTransfers(); if (transfers == null) { transfers = Collections.emptyList(); } final BigDecimal expirationDailyInterest = CoercionHelper.coerce(BigDecimal.class, parameters.getExpirationDailyInterest()); final LocalSettings localSettings = settingsService.getLocalSettings(); final MathContext mathContext = localSettings.getMathContext(); for (final Transfer transfer : transfers) { Calendar trfDate = transfer.getDate(); trfDate = DateUtils.truncate(trfDate, Calendar.DATE); final BigDecimal trfAmount = transfer.getAmount(); BigDecimal actualAmount = trfAmount; final int diffDays = (int) ((trfDate.getTimeInMillis() - expirationDate.getTimeInMillis()) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest actualAmount = actualAmount.subtract(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } remainingAmount = remainingAmount.subtract(actualAmount); lastPaymentDate = (Calendar) trfDate.clone(); } date = DateHelper.truncate(date); BigDecimal remainingAmountAtDate = remainingAmount; final int diffDays = (int) ((date.getTimeInMillis() - (expirationDate.before(lastPaymentDate) ? lastPaymentDate.getTimeInMillis() : expirationDate.getTimeInMillis())) / DateUtils.MILLIS_PER_DAY); if (diffDays > 0 && expirationDailyInterest != null) { // Apply interest remainingAmountAtDate = remainingAmountAtDate.add(remainingAmount.multiply(new BigDecimal(diffDays)) .multiply(expirationDailyInterest.divide(new BigDecimal(100), mathContext))); } final Amount expirationFee = parameters.getExpirationFee(); if (expirationFee != null && (remainingAmountAtDate.compareTo(BigDecimal.ZERO) == 1) && expirationDate.before(date) && (expirationFee.getValue().compareTo(BigDecimal.ZERO) == 1)) { // Apply expiration fee remainingAmountAtDate = remainingAmountAtDate.add(expirationFee.apply(remainingAmount)); } // Round the result ret.setRemainingAmountAtExpirationDate(localSettings.round(remainingAmount)); ret.setRemainingAmountAtDate(localSettings.round(remainingAmountAtDate)); } return ret; }
From source file:com.fujitsu.dc.test.setup.Setup.java
/** * $filter??(Edm.Single)????./*from w ww. j ava 2s . c o m*/ * @param index ??? * @return ??? */ private String getFloatArray(int index) { final BigDecimal singleData = new BigDecimal(1111.11); StringBuilder sbuf = new StringBuilder("["); for (int i = 0; i < index; i++) { if (i == 0) { sbuf.append(String.format("%f", singleData.multiply(new BigDecimal(i)))); } else { sbuf.append(String.format(",%f", singleData.multiply(new BigDecimal(i)))); } } sbuf.append("]"); return sbuf.toString(); }