Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

In this page you can find the example usage for java.math BigDecimal multiply.

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:nl.strohalm.cyclos.entities.accounts.loans.LoanParameters.java

/**
 * Calculates the monthly interests for the given parameters
 * @return 0 if no monthly interests, or the applied interests otherwise (ie: if monthly interests = 1%, paymentCount = 1 and delay = 0, returns
 * 10 for amount = 1000)/* w  w  w.  jav a2  s .  c om*/
 */
public BigDecimal calculateMonthlyInterests(final BigDecimal amount, final int paymentCount, Calendar grantDate,
        Calendar firstExpirationDate, final MathContext mathContext) {
    if (monthlyInterest == null || amount.compareTo(BigDecimal.ZERO) != 1 || paymentCount < 1) {
        return BigDecimal.ZERO;
    }
    // Calculate the delay
    final Calendar now = Calendar.getInstance();
    grantDate = grantDate == null ? now : grantDate;
    firstExpirationDate = firstExpirationDate == null ? (Calendar) now.clone() : firstExpirationDate;
    final Calendar shouldBeFirstExpiration = (Calendar) grantDate.clone();
    shouldBeFirstExpiration.add(Calendar.MONTH, 1);
    int delay = DateHelper.daysBetween(shouldBeFirstExpiration, firstExpirationDate);
    if (delay < 0) {
        delay = 0;
    }

    final BigDecimal grantFee = calculateGrantFee(amount);
    final BigDecimal baseAmount = amount.add(grantFee);
    final BigDecimal interests = monthlyInterest.divide(new BigDecimal(100), mathContext);
    final BigDecimal numerator = new BigDecimal(
            Math.pow(1 + interests.doubleValue(), paymentCount + delay / 30F)).multiply(interests);
    final BigDecimal denominator = new BigDecimal(Math.pow(1 + interests.doubleValue(), paymentCount) - 1);
    final BigDecimal paymentAmount = baseAmount.multiply(numerator).divide(denominator, mathContext);
    final BigDecimal totalAmount = paymentAmount.multiply(new BigDecimal(paymentCount));
    return totalAmount.subtract(baseAmount);
}

From source file:org.kuali.kfs.module.endow.document.service.impl.SecurityServiceImpl.java

/**
 * Computes the unit value based on the market value.
 * /* w  w w. j  a  v  a 2  s  .  c om*/
 * @param security the security for which we calculate the unit value
 * @return the computed unit value
 */
public BigDecimal getSecurityUnitValue(Security security) {
    BigDecimal marketValue = security.getMarketValue();
    BigDecimal unitsHeld = security.getUnitsHeld();
    BigDecimal unitValue = BigDecimal.ZERO;
    ClassCode classCode = security.getClassCode();

    if (ObjectUtils.isNotNull(classCode) && ObjectUtils.isNotNull(unitValue) && ObjectUtils.isNotNull(unitsHeld)
            && unitsHeld.compareTo(BigDecimal.ZERO) != 0) {
        if (EndowConstants.ClassCodeTypes.BOND.equalsIgnoreCase(classCode.getClassCodeType())) {
            unitValue = KEMCalculationRoundingHelper.divide((marketValue.multiply(new BigDecimal(100))),
                    unitsHeld, EndowConstants.Scale.SECURITY_UNIT_VALUE);
        } else {
            unitValue = KEMCalculationRoundingHelper.divide(marketValue, unitsHeld,
                    EndowConstants.Scale.SECURITY_UNIT_VALUE);
        }
    }

    return unitValue;
}

From source file:org.broadleafcommerce.core.pricing.service.workflow.FulfillmentItemPricingActivity.java

/**
 * Distributes the order adjustments (if any) to the individual fulfillment group items.
 * @param order/*from  ww  w.  ja v a 2s  . co m*/
 * @param totalAllItems
 * @return
 */
protected Money distributeOrderSavingsToItems(Order order, BigDecimal totalAllItems) {
    Money returnAmount = new Money(order.getCurrency());

    BigDecimal orderAdjAmt = order.getOrderAdjustmentsValue().getAmount();

    for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
        for (FulfillmentGroupItem fgItem : fulfillmentGroup.getFulfillmentGroupItems()) {
            BigDecimal fgItemAmount = fgItem.getTotalItemAmount().getAmount();
            BigDecimal proratedAdjAmt = totalAllItems.compareTo(BigDecimal.ZERO) == 0 ? totalAllItems
                    : orderAdjAmt.multiply(fgItemAmount).divide(totalAllItems, RoundingMode.FLOOR);
            fgItem.setProratedOrderAdjustmentAmount(new Money(proratedAdjAmt, order.getCurrency()));
            returnAmount = returnAmount.add(fgItem.getProratedOrderAdjustmentAmount());
        }
    }
    return returnAmount;
}

From source file:org.collectionspace.chain.csp.webui.nuispec.DataGenerator.java

/**
 * pick a random valid date between the defaults defined
 * @return//from ww w.  j  a v a2 s.  c  o m
 */
private Date randomDate() {
    BigDecimal retValue = null;
    BigDecimal length = maxValue.subtract(minValue);
    BigDecimal factor = new BigDecimal(random.nextDouble());
    retValue = length.multiply(factor).add(minValue);
    return new Date(retValue.toBigInteger().longValue());
}

From source file:com.sammyun.plugin.PaymentPlugin.java

/**
 * //from   www. j  a va  2 s . com
 * 
 * @param amount ?
 * @return 
 */
public BigDecimal calculateFee(BigDecimal amount) {
    Setting setting = SettingUtils.get();
    BigDecimal fee;
    if (getFeeType() == FeeType.scale) {
        fee = amount.multiply(getFee());
    } else {
        fee = getFee();
    }
    //return setting.setScale(fee);
    return fee;
}

From source file:edu.macalester.tagrelatedness.KendallsCorrelation.java

public BigDecimal get(BigDecimal n) {

    // Make sure n is a positive number

    if (n.compareTo(ZERO) <= 0) {
        throw new IllegalArgumentException();
    }//from w ww  .  ja v a  2 s  .com

    BigDecimal initialGuess = getInitialApproximation(n);
    trace("Initial guess " + initialGuess.toString());
    BigDecimal lastGuess = ZERO;
    BigDecimal guess = new BigDecimal(initialGuess.toString());

    // Iterate

    iterations = 0;
    boolean more = true;
    while (more) {
        lastGuess = guess;
        guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP);
        guess = guess.add(lastGuess);
        guess = guess.divide(TWO, scale, BigDecimal.ROUND_HALF_UP);
        trace("Next guess " + guess.toString());
        error = n.subtract(guess.multiply(guess));
        if (++iterations >= maxIterations) {
            more = false;
        } else if (lastGuess.equals(guess)) {
            more = error.abs().compareTo(ONE) >= 0;
        }
    }
    return guess;

}

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 www.  j ava 2  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:org.kuali.ole.fp.document.service.impl.DisbursementVoucherTaxServiceImpl.java

/**
 * This method generates non-resident alien (NRA) tax lines for the given disbursement voucher.  
 * /*from  w ww  .j ava  2 s .c o  m*/
 * The NRA tax lines consist of three possible sets of tax lines: 
 * - Gross up tax lines
 * - Federal tax lines
 * - State tax lines
 * 
 * Gross up tax lines are generated if the income tax gross up code is set on the DisbursementVoucherNonResidentAlienTax 
 * attribute of the disbursement voucher.
 * 
 * Federal tax lines are generated if the federal tax rate in the DisbursementVoucherNonResidentAlienTax attribute is
 * other than zero.
 * 
 * State tax lines are generated if the state tax rate in the DisbursementVoucherNonResidentAlienTax attribute is
 * other than zero.
 * 
 * @param document The disbursement voucher the NRA tax lines will be added to.
 * 
 * @see org.kuali.ole.fp.document.service.DisbursementVoucherTaxService#generateNRATaxLines(org.kuali.ole.fp.document.DisbursementVoucherDocument)
 */
protected void generateNRATaxLines(DisbursementVoucherDocument document) {
    // retrieve first accounting line for tax line attributes
    AccountingLine line1 = document.getSourceAccountingLine(0);

    List taxLineNumbers = new ArrayList();

    // generate gross up
    if (document.getDvNonResidentAlienTax().isIncomeTaxGrossUpCode()) {
        AccountingLine grossLine = null;
        try {
            grossLine = (SourceAccountingLine) document.getSourceAccountingLineClass().newInstance();
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("unable to access sourceAccountingLineClass", e);
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("unable to instantiate sourceAccountingLineClass", e);
        }

        grossLine.setDocumentNumber(document.getDocumentNumber());
        grossLine.setSequenceNumber(document.getNextSourceLineNumber());
        grossLine.setChartOfAccountsCode(line1.getChartOfAccountsCode());
        grossLine.setAccountNumber(line1.getAccountNumber());
        grossLine.setFinancialObjectCode(line1.getFinancialObjectCode());

        // calculate gross up amount and set as line amount
        BigDecimal federalTaxPercent = document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent()
                .bigDecimalValue();
        BigDecimal stateTaxPercent = document.getDvNonResidentAlienTax().getStateIncomeTaxPercent()
                .bigDecimalValue();
        BigDecimal documentAmount = document.getDisbVchrCheckTotalAmount().bigDecimalValue();

        KualiDecimal grossAmount1 = new KualiDecimal((documentAmount.multiply(federalTaxPercent).divide(
                new BigDecimal(100).subtract(federalTaxPercent).subtract(stateTaxPercent), 5,
                BigDecimal.ROUND_HALF_UP)));
        KualiDecimal grossAmount2 = new KualiDecimal((documentAmount.multiply(stateTaxPercent).divide(
                new BigDecimal(100).subtract(federalTaxPercent).subtract(stateTaxPercent), 5,
                BigDecimal.ROUND_HALF_UP)));
        grossLine.setAmount(grossAmount1.add(grossAmount2));

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(grossLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        grossLine.refresh();
        document.getSourceAccountingLines().add(grossLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(document.getDisbVchrCheckTotalAmount().add(grossLine.getAmount()));
    }

    KualiDecimal taxableAmount = document.getDisbVchrCheckTotalAmount();

    // generate federal tax line
    if (!(KualiDecimal.ZERO.equals(document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent()))) {
        String federalTaxChart = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_CHART_SUFFIX);
        String federalTaxAccount = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_ACCOUNT_SUFFIX);
        String federalTaxObjectCode = parameterService.getSubParameterValueAsString(
                DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.FEDERAL_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                document.getDvNonResidentAlienTax().getIncomeClassCode());
        if (StringUtils.isBlank(federalTaxChart) || StringUtils.isBlank(federalTaxAccount)
                || StringUtils.isBlank(federalTaxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }

        AccountingLine federalTaxLine = generateTaxAccountingLine(document, federalTaxChart, federalTaxAccount,
                federalTaxObjectCode, document.getDvNonResidentAlienTax().getFederalIncomeTaxPercent(),
                taxableAmount);

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(federalTaxLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        federalTaxLine.refresh();
        document.getSourceAccountingLines().add(federalTaxLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(
                document.getDisbVchrCheckTotalAmount().add(federalTaxLine.getAmount()));
    }

    // generate state tax line
    if (!(KualiDecimal.ZERO.equals(document.getDvNonResidentAlienTax().getStateIncomeTaxPercent()))) {
        String stateTaxChart = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_CHART_SUFFIX);
        String stateTaxAccount = parameterService.getParameterValueAsString(DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_ACCOUNT_SUFFIX);
        String stateTaxObjectCode = parameterService.getSubParameterValueAsString(
                DisbursementVoucherDocument.class,
                DisbursementVoucherConstants.STATE_TAX_PARM_PREFIX
                        + DisbursementVoucherConstants.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                document.getDvNonResidentAlienTax().getIncomeClassCode());

        if (StringUtils.isBlank(stateTaxChart) || StringUtils.isBlank(stateTaxAccount)
                || StringUtils.isBlank(stateTaxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }

        AccountingLine stateTaxLine = generateTaxAccountingLine(document, stateTaxChart, stateTaxAccount,
                stateTaxObjectCode, document.getDvNonResidentAlienTax().getStateIncomeTaxPercent(),
                taxableAmount);

        // put line number in line number list, and update next line property in document
        taxLineNumbers.add(stateTaxLine.getSequenceNumber());
        document.setNextSourceLineNumber(new Integer(document.getNextSourceLineNumber().intValue() + 1));

        // add to source accounting lines
        stateTaxLine.refresh();
        document.getSourceAccountingLines().add(stateTaxLine);

        // update check total, is added because line amount is negative, so this will take check amount down
        document.setDisbVchrCheckTotalAmount(
                document.getDisbVchrCheckTotalAmount().add(stateTaxLine.getAmount()));
    }

    // update line number field
    document.getDvNonResidentAlienTax()
            .setFinancialDocumentAccountingLineText(StringUtils.join(taxLineNumbers.iterator(), ","));
}

From source file:CentralLimitTheorem.CLT.java

public void ModelDynamics(int size, double prob) {
    sampleSize = size;//from   w w w. j av  a 2s  .  c  o  m
    probability = prob;
    double m = sampleSize * probability;
    double variance_2 = sampleSize * probability * (1. - probability);
    for (int i = 0; i <= 1000; i++) {
        double x = (double) i * ((double) sampleSize / 1000.);
        double exponent = Math.pow(x - m, 2.0) / (2 * variance_2);
        double scale = Math.exp((-1.) * exponent);
        double coeff = Math.sqrt(variance_2 * 2. * Math.PI);
        BigDecimal coeffBD = new BigDecimal(coeff);
        BigDecimal scaleBD = new BigDecimal(scale);
        prob_x[i] = scaleBD.divide(coeffBD, 40, RoundingMode.HALF_UP);

    }

    for (int i = 0; i <= sampleSize; i++) {
        BigInteger ntF = factorial(sampleSize);
        BigInteger denom = factorial(i).multiply(factorial(sampleSize - i));
        BigDecimal ntFBD = new BigDecimal(ntF);
        BigDecimal denomBD = new BigDecimal(denom);
        BigDecimal quotient = ntFBD.divide(denomBD, 40, RoundingMode.HALF_UP);
        BigDecimal restBD = BigDecimal.valueOf(
                Math.pow(probability, (double) i) * Math.pow(1. - probability, (double) sampleSize - i));
        prob_k[i] = quotient.multiply(restBD);
        System.out.format("[%d]\t%.20f\n", i, prob_k[i]);
    }

}

From source file:de.csdev.ebus.command.datatypes.ext.EBusTypeTime.java

@Override
public EBusDateTime decodeInt(byte[] data) throws EBusTypeException {

    Calendar calendar = new GregorianCalendar(1970, 0, 1, 0, 0, 0);

    BigDecimal second = null;/*from   ww w. jav a2 s  .  co  m*/
    BigDecimal minute = null;
    BigDecimal hour = null;

    if (data.length != getTypeLength()) {
        throw new EBusTypeException("Input byte array must have a length of %d bytes!", getTypeLength());
    }

    if (StringUtils.equals(variant, SHORT)) {
        IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
        minute = bcdType.decode(new byte[] { data[0] });
        hour = bcdType.decode(new byte[] { data[1] });

    } else if (StringUtils.equals(variant, DEFAULT)) {
        IEBusType<BigDecimal> bcdType = types.getType(EBusTypeBCD.TYPE_BCD);
        second = bcdType.decode(new byte[] { data[0] });
        minute = bcdType.decode(new byte[] { data[1] });
        hour = bcdType.decode(new byte[] { data[2] });

    } else if (StringUtils.equals(variant, HEX)) {
        IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);
        second = charType.decode(new byte[] { data[0] });
        minute = charType.decode(new byte[] { data[1] });
        hour = charType.decode(new byte[] { data[2] });

    } else if (StringUtils.equals(variant, HEX_SHORT)) {
        IEBusType<BigDecimal> charType = types.getType(EBusTypeChar.TYPE_CHAR);
        minute = charType.decode(new byte[] { data[0] });
        hour = charType.decode(new byte[] { data[1] });

    } else if (StringUtils.equals(variant, MINUTES) || StringUtils.equals(variant, MINUTES_SHORT)) {

        BigDecimal minutesSinceMidnight = null;
        if (StringUtils.equals(variant, MINUTES_SHORT)) {
            IEBusType<BigDecimal> type = types.getType(EBusTypeUnsignedNumber.TYPE_UNUMBER, IEBusType.LENGTH,
                    1);
            minutesSinceMidnight = type.decode(data);
        } else {
            IEBusType<BigDecimal> type = types.getType(EBusTypeUnsignedNumber.TYPE_UNUMBER, IEBusType.LENGTH,
                    2);
            minutesSinceMidnight = type.decode(data);
        }

        minutesSinceMidnight = minutesSinceMidnight.multiply(minuteMultiplier);

        if (minutesSinceMidnight.intValue() > 1440) {
            throw new EBusTypeException("Value 'minutes since midnight' to large!");
        }

        calendar.add(Calendar.MINUTE, minutesSinceMidnight.intValue());
    }

    if (second != null) {
        calendar.set(Calendar.SECOND, second.intValue());
    }
    if (minute != null) {
        calendar.set(Calendar.MINUTE, minute.intValue());
    }
    if (hour != null) {
        calendar.set(Calendar.HOUR_OF_DAY, hour.intValue());
    }

    return new EBusDateTime(calendar, true, false);
}