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:org.kuali.kfs.gl.batch.service.impl.PosterServiceImpl.java

/**
 * Generates the description of a charge
 *
 * @param rate the ICR rate for this entry
 * @param objectCode the object code of this entry
 * @param type the ICR type code of this entry's account
 * @param amount the amount of this entry
 * @return a description for the charge entry
 *//* w  w w. j  av  a  2s.co  m*/
protected String getChargeDescription(BigDecimal rate, String objectCode, String type, KualiDecimal amount) {
    BigDecimal newRate = rate.multiply(PosterServiceImpl.BDONEHUNDRED);

    StringBuffer desc = new StringBuffer("CHG ");
    if (newRate.doubleValue() < 10) {
        desc.append(" ");
    }
    desc.append(DFPCT.format(newRate));
    desc.append("% ON ");
    desc.append(objectCode);
    desc.append(" (");
    desc.append(type);
    desc.append(")  ");
    String amt = DFAMT.format(amount);
    while (amt.length() < 13) {
        amt = " " + amt;
    }
    desc.append(amt);
    return desc.toString();
}

From source file:org.mifosplatform.portfolio.loanaccount.domain.LoanCharge.java

public void update(final BigDecimal amount, final LocalDate dueDate, final BigDecimal loanPrincipal,
        Integer numberOfRepayments, BigDecimal loanCharge) {
    if (dueDate != null) {
        this.dueDate = dueDate.toDate();
    }/*ww w  .  ja  v a 2 s. c o m*/

    if (amount != null) {
        switch (ChargeCalculationType.fromInt(this.chargeCalculation)) {
        case INVALID:
            break;
        case FLAT:
            if (isInstalmentFee()) {
                if (numberOfRepayments == null) {
                    numberOfRepayments = this.loan.repaymentScheduleDetail().getNumberOfRepayments();
                }
                this.amount = amount.multiply(BigDecimal.valueOf(numberOfRepayments));
            } else {
                this.amount = amount;
            }
            break;
        case PERCENT_OF_AMOUNT:
        case PERCENT_OF_AMOUNT_AND_INTEREST:
        case PERCENT_OF_INTEREST:
            this.percentage = amount;
            this.amountPercentageAppliedTo = loanPrincipal;
            if (loanCharge.compareTo(BigDecimal.ZERO) == 0) {
                loanCharge = percentageOf(this.amountPercentageAppliedTo);
            }
            this.amount = minimumAndMaximumCap(loanCharge);
            this.amountOutstanding = calculateOutstanding();
            break;
        }
        this.amountOrPercentage = amount;
        if (this.loan != null && isInstalmentFee()) {
            final Set<LoanInstallmentCharge> chargePerInstallments = this.loan
                    .generateInstallmentLoanCharges(this);
            if (this.loanInstallmentCharge.isEmpty()) {
                this.loanInstallmentCharge.addAll(chargePerInstallments);
            } else {
                int index = 0;
                final LoanInstallmentCharge[] loanChargePerInstallments = new LoanInstallmentCharge[chargePerInstallments
                        .size()];
                final LoanInstallmentCharge[] loanChargePerInstallmentArray = chargePerInstallments
                        .toArray(loanChargePerInstallments);
                for (final LoanInstallmentCharge chargePerInstallment : this.loanInstallmentCharge) {
                    chargePerInstallment.copyFrom(loanChargePerInstallmentArray[index++]);
                }
            }
        }
    }
}

From source file:nl.b3p.kaartenbalie.struts.DepositAction.java

@Override
public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*from  w ww  .j ava2 s .c  o m*/

    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        super.addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    /*
     * Alle gegevens voor de betaling.
     */
    Integer amount = (Integer) dynaForm.get("amount");
    Integer fraction = (Integer) dynaForm.get("fraction");
    String description = dynaForm.getString("description");
    String paymentMethod = dynaForm.getString("paymentMethod");
    BigDecimal billing = integersToBD(amount, fraction);
    Integer exchangeRate = Transaction.getExchangeRate();
    if (billing.doubleValue() <= 0) {
        log.error("Amount cannot be less then or equal to zero!");
        throw new Exception("Amount cannot be less then or equal to zero!");
    }

    /*
     * Start de transactie
     */
    StringBuffer tdesc = new StringBuffer();
    if (description != null) {
        tdesc.append(description);
    }
    if (paymentMethod != null) {
        tdesc.append("/");
        tdesc.append(paymentMethod);
    }
    if (exchangeRate != null) {
        tdesc.append("/1:");
        tdesc.append(exchangeRate);
    }
    if (tdesc.length() > 32) {
        tdesc = new StringBuffer(tdesc.substring(0, 32));
    }
    Organization organization = getOrganization(dynaForm, request);
    AccountManager am = AccountManager.getAccountManager(organization.getId());

    /* Er komt null terug als accounting uit staat in AccountManager.java */
    Transaction tpd = am.prepareTransaction(Transaction.DEPOSIT, tdesc.toString());

    /* Prijs, koers, conversie */
    if (tpd != null) {
        tpd.setBillingAmount(billing);
        BigDecimal creditAlt = billing.multiply(new BigDecimal(exchangeRate.intValue()));
        tpd.setCreditAlteration(creditAlt);
        tpd.setTxExchangeRate(exchangeRate);
        am.commitTransaction(tpd, (User) request.getUserPrincipal());
    }

    ActionRedirect redirect = new ActionRedirect(mapping.findForward(BACK));
    redirect.addParameter("selectedOrganization", organization.getId().toString());

    return redirect;
}

From source file:org.kuali.kfs.gl.batch.service.impl.PosterServiceImpl.java

/**
 * Returns the description of a debit origin entry created by generateTransactions
 *
 * @param rate the ICR rate that relates to this entry
 * @param amount the amount of this entry
 * @param chartOfAccountsCode the chart codce of the debit entry
 * @param accountNumber the account number of the debit entry
 * @return a description for the debit entry
 *//*from  ww w . j  av a2  s.  c o  m*/
protected String getOffsetDescription(BigDecimal rate, KualiDecimal amount, String chartOfAccountsCode,
        String accountNumber) {
    BigDecimal newRate = rate.multiply(PosterServiceImpl.BDONEHUNDRED);

    StringBuffer desc = new StringBuffer("RCV ");
    if (newRate.doubleValue() < 10) {
        desc.append(" ");
    }
    desc.append(DFPCT.format(newRate));
    desc.append("% ON ");
    String amt = DFAMT.format(amount);
    while (amt.length() < 13) {
        amt = " " + amt;
    }
    desc.append(amt);
    desc.append(" FRM ");
    // desc.append(chartOfAccountsCode);
    // desc.append("-");
    desc.append(accountNumber);
    return desc.toString();
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Power function.//ww  w. j av a  2s. c o m
 *
 * @param x Base of the power.
 * @param y Exponent of the power.
 * @return x^y.
 * The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x|
 */
static public BigDecimal pow(final BigDecimal x, final BigDecimal y) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("Cannot power negative " + x.toString());
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* return x^y = exp(y*log(x)) ;
         */
        BigDecimal logx = log(x);
        BigDecimal ylogx = y.multiply(logx);
        BigDecimal resul = exp(ylogx);
        /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x|
         */
        double errR = Math.abs(logx.doubleValue() * y.ulp().doubleValue() / 2.)
                + Math.abs(y.doubleValue() * x.ulp().doubleValue() / 2. / x.doubleValue());
        MathContext mcR = new MathContext(err2prec(1.0, errR));
        return resul.round(mcR);
    }
}

From source file:org.broadleafcommerce.core.pricing.service.module.BandedShippingModule.java

private void calculateShipping(FulfillmentGroup fulfillmentGroup) {
    if (!isValidModuleForService(fulfillmentGroup.getService()) && !isDefaultModule()) {
        LOG.info("fulfillment group (" + fulfillmentGroup.getId() + ") with a service type of ("
                + fulfillmentGroup.getService() + ") is not valid for this module service type ("
                + getServiceName() + ")");
        return;/*from  www . j  a  v a 2s  .c  o m*/
    }
    if (fulfillmentGroup.getFulfillmentGroupItems().size() == 0) {
        LOG.warn("fulfillment group (" + fulfillmentGroup.getId()
                + ") does not contain any fulfillment group items. Unable to price banded shipping");
        fulfillmentGroup.setShippingPrice(
                BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, fulfillmentGroup.getOrder().getCurrency()));
        fulfillmentGroup.setSaleShippingPrice(
                BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, fulfillmentGroup.getOrder().getCurrency()));
        fulfillmentGroup.setRetailShippingPrice(
                BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, fulfillmentGroup.getOrder().getCurrency()));
        return;
    }
    Address address = fulfillmentGroup.getAddress();
    String state = null;
    if (StringUtils.isNotBlank(address.getStateProvinceRegion())) {
        state = address.getStateProvinceRegion();
    } else if (address.getState() != null) {
        state = address.getState().getAbbreviation();
    }

    BigDecimal retailTotal = new BigDecimal(0);
    String feeType = feeTypeMapping.get(fulfillmentGroup.getMethod());
    String feeSubType = ((feeSubTypeMapping.get(state) == null) ? feeSubTypeMapping.get("ALL")
            : feeSubTypeMapping.get(state));

    for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) {
        BigDecimal price = (fulfillmentGroupItem.getRetailPrice() != null) ? fulfillmentGroupItem
                .getRetailPrice().getAmount().multiply(BigDecimal.valueOf(fulfillmentGroupItem.getQuantity()))
                : null;
        if (price == null) {
            price = fulfillmentGroupItem.getOrderItem().getRetailPrice().getAmount()
                    .multiply(BigDecimal.valueOf(fulfillmentGroupItem.getQuantity()));
        }
        retailTotal = retailTotal.add(price);
    }

    ShippingRate sr = shippingRateService.readShippingRateByFeeTypesUnityQty(feeType, feeSubType, retailTotal);
    if (sr == null) {
        throw new NotImplementedException("Shipping rate " + fulfillmentGroup.getMethod() + " not supported");
    }
    BigDecimal shippingPrice = new BigDecimal(0);
    if (sr.getBandResultPercent().compareTo(0) > 0) {
        BigDecimal percent = new BigDecimal(sr.getBandResultPercent() / 100);
        shippingPrice = retailTotal.multiply(percent);
    } else {
        shippingPrice = sr.getBandResultQuantity();
    }
    fulfillmentGroup.setShippingPrice(
            BroadleafCurrencyUtils.getMoney(shippingPrice, fulfillmentGroup.getOrder().getCurrency()));
    fulfillmentGroup.setSaleShippingPrice(fulfillmentGroup.getShippingPrice());
    fulfillmentGroup.setRetailShippingPrice(fulfillmentGroup.getSaleShippingPrice());
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

private void updateTrxLegacyCosts(Costing _cost, int standardPrecision, Set<String> naturalTree) {
    log4j.debug("****** UpdateTrxLegacyCosts");
    Costing cost = OBDal.getInstance().get(Costing.class, _cost.getId());

    StringBuffer where = new StringBuffer();
    where.append(MaterialTransaction.PROPERTY_PRODUCT + ".id = :product");
    where.append("   and " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " >= :dateFrom");
    where.append("   and " + MaterialTransaction.PROPERTY_MOVEMENTDATE + " < :dateTo");
    OBQuery<MaterialTransaction> trxQry = OBDal.getInstance().createQuery(MaterialTransaction.class,
            where.toString());/*from  ww  w  .  j ava2 s. c  om*/
    trxQry.setFilterOnActive(false);
    trxQry.setFilterOnReadableClients(false);
    trxQry.setFilterOnReadableOrganization(false);
    trxQry.setNamedParameter("product", DalUtil.getId(cost.getProduct()));
    trxQry.setNamedParameter("orgs", naturalTree);
    trxQry.setNamedParameter("dateFrom", cost.getStartingDate());
    trxQry.setNamedParameter("dateTo", cost.getEndingDate());
    trxQry.setFetchSize(1000);

    ScrollableResults trxs = trxQry.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    try {
        while (trxs.next()) {
            MaterialTransaction trx = (MaterialTransaction) trxs.get(0);
            log4j.debug("********** UpdateTrxLegacyCosts process trx:" + trx.getIdentifier());

            if (trx.getGoodsShipmentLine() != null && trx.getGoodsShipmentLine().getShipmentReceipt()
                    .getAccountingDate().compareTo(trx.getMovementDate()) != 0) {
                // Shipments with accounting date different than the movement date gets the cost valid on
                // the accounting date.
                BigDecimal unitCost = new BigDecimal(
                        new ProductInfo(cost.getProduct().getId(), new DalConnectionProvider(false))
                                .getProductItemCost(
                                        OBDateUtils.formatDate(trx.getGoodsShipmentLine().getShipmentReceipt()
                                                .getAccountingDate()),
                                        null, "AV", new DalConnectionProvider(false),
                                        OBDal.getInstance().getConnection()));
                BigDecimal trxCost = unitCost.multiply(trx.getMovementQuantity().abs())
                        .setScale(standardPrecision, BigDecimal.ROUND_HALF_UP);

                trx.setTransactionCost(trxCost);
            } else {
                trx.setTransactionCost(cost.getCost().multiply(trx.getMovementQuantity().abs())
                        .setScale(standardPrecision, BigDecimal.ROUND_HALF_UP));
            }

            trx.setCurrency(cost.getCurrency());
            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");

            if ((i % 100) == 0) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                cost = OBDal.getInstance().get(Costing.class, cost.getId());
            }
            i++;
        }
    } finally {
        trxs.close();
    }

    log4j.debug("****** UpdateTrxLegacyCosts updated:" + i);
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Pochhammers function./*from  ww w .  j  a va 2s .  c  om*/
 *
 * @param x The main argument.
 * @param n The non-negative index.
 * @return (x)_n = x(x+1)(x+2)*...*(x+n-1).
 */
static public BigDecimal pochhammer(final BigDecimal x, final int n) {
    /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
     */
    if (n < 0) {
        throw new ProviderException("Unimplemented pochhammer with negative index " + n);
    } else if (n == 0) {
        return BigDecimal.ONE;
    } else {
        /* internally two safety digits
         */
        BigDecimal xhighpr = scalePrec(x, 2);
        BigDecimal resul = xhighpr;

        double xUlpDbl = x.ulp().doubleValue();

        double xDbl = x.doubleValue();
        /* relative error of the result is the sum of the relative errors of the factors
         */

        double eps = 0.5 * xUlpDbl / Math.abs(xDbl);

        for (int i = 1; i < n; i++) {
            eps += 0.5 * xUlpDbl / Math.abs(xDbl + i);

            resul = resul.multiply(xhighpr.add(new BigDecimal(i)));
            final MathContext mcloc = new MathContext(4 + err2prec(eps));
            resul = resul.round(mcloc);

        }
        return resul.round(new MathContext(err2prec(eps)));

    }
}

From source file:com.aimluck.eip.project.ProjectTaskSelectData.java

/**
 * ResultData???? <BR>//w w w  . j a  va  2s.  c  o  m
 *
 * @param record
 *          
 * @return ResultData
 */
@Override
protected Object getResultData(EipTProjectTask record) {
    ProjectTaskResultData data = ProjectUtils.getProjectTaskResultData(record);
    Integer taskId = (int) data.getTaskId().getValue();

    // ?
    int cntChild = ProjectUtils.getCountChildrenTask(taskId);

    // ??2??true
    // ??
    data.setHasChildren(cntChild >= 2);

    // ?
    data.setHasChildrenForForm(cntChild > 0);

    // ?
    int lapsedDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(Calendar.getInstance().getTime()));
    // 
    int taskDays = ProjectUtils.getLapsedDays(ProjectUtils.toString(record.getStartPlanDate()),
            ProjectUtils.toString(record.getEndPlanDate()));
    data.setPlanTerm(taskDays);

    if (lapsedDays > taskDays) {
        // ???
        lapsedDays = taskDays;
    }

    // ?
    data.setPlanProgressRate(ProjectUtils.getPlanWorkload(lapsedDays, taskDays));

    // 
    List<ProjectTaskMemberResultData> memberList = data.getMemberList();
    BigDecimal workload = BigDecimal.valueOf(0);
    workload = workload.setScale(1);
    for (int i = 0; i < memberList.size(); i++) {
        ProjectTaskMemberResultData member = memberList.get(i);
        workload = workload.add(member.getWorkload());
    }
    data.setWorkload(workload);

    // 
    BigDecimal forecastWorkload = BigDecimal.valueOf(0);
    if (data.getProgressRate().getValue() != 0) {
        forecastWorkload = workload.multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(data.getProgressRate().getValue()), 2, BigDecimal.ROUND_HALF_UP);
    }
    data.setForecastWorkload(forecastWorkload);

    // 
    data.setIndentFlg(indentFlg);

    data.setEditable(ProjectFormUtils.isEditable(taskId, loginUserId));

    return data;
}

From source file:org.kuali.kfs.module.bc.document.service.impl.SalarySettingServiceImpl.java

/**
 * @see org.kuali.kfs.module.bc.document.service.SalarySettingService#calculateAnnualPayAmount(org.kuali.kfs.module.bc.businessobject.PendingBudgetConstructionAppointmentFunding)
 *//*from  w  w w .  j  a v a2 s.co m*/
public KualiInteger calculateAnnualPayAmount(PendingBudgetConstructionAppointmentFunding appointmentFunding) {
    LOG.debug("calculateAnnualPayAmount() start");

    KualiInteger annualPayAmount = KualiInteger.ZERO;
    BigDecimal hourlyPayRate = appointmentFunding.getAppointmentRequestedPayRate();
    BigDecimal fteQuantity = this.calculateFteQuantityFromAppointmentFunding(appointmentFunding);
    if (fteQuantity.compareTo(BigDecimal.ZERO) == 0) {
        // revert to entered amount for zero FTE to allow error message
        annualPayAmount = appointmentFunding.getAppointmentRequestedAmount();
    } else {
        BigDecimal annualWorkingHours = BigDecimal.valueOf(BudgetParameterFinder.getAnnualWorkingHours());
        BigDecimal totalPayHoursForYear = fteQuantity.multiply(annualWorkingHours);
        annualPayAmount = new KualiInteger(hourlyPayRate.multiply(totalPayHoursForYear));
    }

    return annualPayAmount;
}