Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:com.heliumv.api.inventory.InventoryApi.java

private boolean isDifferenceToLarge(BigDecimal baseAmount, BigDecimal newAmount) {
    BigDecimal percentAllowed = new BigDecimal(10);
    BigDecimal amplitude = baseAmount.movePointLeft(2).multiply(percentAllowed);
    if (amplitude.compareTo(BigDecimal.ONE) <= 0) {
        amplitude = BigDecimal.ONE;
    }/*ww w . ja v  a  2 s .co m*/
    return baseAmount.subtract(newAmount).abs().compareTo(amplitude) > 0;
}

From source file:org.egov.works.web.actions.revisionEstimate.SearchRevisionEstimateAction.java

private void validateARFForRE(final RevisionAbstractEstimate revisionEstimate) {
    String arfNo = "";
    BigDecimal advanceAmount = new BigDecimal(0);
    final List<WorkOrderEstimate> woeList = persistenceService.findAllBy(
            " from WorkOrderEstimate woe where woe.workOrder.egwStatus.code = 'APPROVED' and woe.estimate=?",
            revisionEstimate.getParent());
    if (woeList != null && !woeList.isEmpty())
        for (final WorkOrderEstimate woe : woeList)
            for (final ContractorAdvanceRequisition arf : woe.getContractorAdvanceRequisitions())
                if (!arf.getStatus().getCode().equalsIgnoreCase(
                        ContractorAdvanceRequisition.ContractorAdvanceRequisitionStatus.CANCELLED.toString())) {
                    advanceAmount = advanceAmount.add(arf.getAdvanceRequisitionAmount());
                    if (!arfNo.equals(""))
                        arfNo = arfNo.concat(", ").concat(arf.getAdvanceRequisitionNumber());
                    else
                        arfNo = arfNo.concat(arf.getAdvanceRequisitionNumber());
                }/*w  w  w . j  a  v  a 2  s .  c  o m*/
    if (!arfNo.equals("")) {
        final BigDecimal totalEstimateValueIncludingRE = contractorAdvanceService
                .getTotalEstimateValueIncludingRE(revisionEstimate.getParent());
        if (totalEstimateValueIncludingRE.subtract(new BigDecimal(revisionEstimate.getTotalAmount().getValue()))
                .longValue() < advanceAmount.longValue())
            throw new ValidationException(Arrays.asList(new ValidationError("cancelRE.arf.created.message",
                    getText("cancelRE.arf.created.message", new String[] { arfNo }))));
    }
}

From source file:com.benfante.minimark.blo.ResultCalculationBo.java

private void evaluateClosedQuestion(ClosedQuestionFilling closedQuestionFilling, String evaluationType,
        BigDecimal minimumEvaluation) {
    BigDecimal result = new BigDecimal("0.00");
    if (evaluationType == null
            || Assessment.EVALUATION_CLOSED_SUM_CORRECT_MINUS_WRONG_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        final BigDecimal weightWrong = closedQuestionFilling.weightWrongAnswers();
        final BigDecimal weightSelectedWrong = closedQuestionFilling.weightSelectedWrongAnswers();
        BigDecimal normalizedCorrect = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // nc = #selectedCorrect/#correct
            normalizedCorrect = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }/*from  w w w .  j  a  v a2 s . co  m*/
        BigDecimal normalizedWrong = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightWrong)) {
            // nw = #selectedWrong/#wrong
            normalizedWrong = weightSelectedWrong.divide(weightWrong, 2, RoundingMode.HALF_EVEN);
        }
        // r = nc-nw
        result = normalizedCorrect.subtract(normalizedWrong);
    } else if (Assessment.EVALUATION_CLOSED_SUM_CORRECT_ANSWERS.equals(evaluationType)) {
        final BigDecimal weightCorrect = closedQuestionFilling.weightCorrectAnswers();
        final BigDecimal weightSelectedCorrect = closedQuestionFilling.weightSelectedCorrectAnswers();
        result = new BigDecimal("1.00");
        if (!BigDecimal.ZERO.equals(weightCorrect)) {
            // r = #selectedCorrect/#correct
            result = weightSelectedCorrect.divide(weightCorrect, 2, RoundingMode.HALF_EVEN);
        }
    }
    // r = max(r, minimumEvaluation)
    if (minimumEvaluation != null) {
        result = result.max(minimumEvaluation);
    }
    closedQuestionFilling.setMark(result);
}

From source file:org.talend.dataprep.transformation.actions.math.NumericOperations.java

protected String compute(final String stringOperandOne, final String operator, final String stringOperandTwo) {
    if (!NumericHelper.isBigDecimal(stringOperandOne) || !NumericHelper.isBigDecimal(stringOperandTwo)) {
        return StringUtils.EMPTY;
    }/*  w ww. j  av a  2  s . c o m*/

    try {
        final BigDecimal operandOne = BigDecimalParser.toBigDecimal(stringOperandOne);
        final BigDecimal operandTwo = BigDecimalParser.toBigDecimal(stringOperandTwo);

        BigDecimal toReturn;

        final int scale = 2;
        final RoundingMode rm = HALF_UP;

        switch (operator) {
        case PLUS:
            toReturn = operandOne.add(operandTwo);
            break;
        case MULTIPLY:
            toReturn = operandOne.multiply(operandTwo);
            break;
        case MINUS:
            toReturn = operandOne.subtract(operandTwo);
            break;
        case DIVIDE:
            toReturn = operandOne.divide(operandTwo, scale, rm);
            break;
        default:
            return "";
        }

        // Format result:
        return toReturn.setScale(scale, rm).stripTrailingZeros().toPlainString();
    } catch (ArithmeticException | NullPointerException e) {
        return StringUtils.EMPTY;
    }
}

From source file:com.salesmanager.core.module.impl.application.prices.MonthlyPriceModule.java

public OrderTotalSummary calculateOrderPrice(Order order, OrderTotalSummary orderSummary,
        OrderProduct orderProduct, OrderProductPrice productPrice, String currency, Locale locale) {

    /**/*from w ww . j a  v a 2s  .  c om*/
     * Monthly price goes in the oneTime fees as well as in the upcoming
     * recursive fees
     */

    BigDecimal finalPrice = null;
    BigDecimal discountPrice = null;

    BigDecimal originalPrice = orderProduct.getOriginalProductPrice();
    if (!productPrice.isDefaultPrice()) {
        originalPrice = productPrice.getProductPriceAmount();
    }

    int quantity = orderProduct.getProductQuantity();

    // the real price is the price submited
    finalPrice = orderProduct.getProductPrice();
    finalPrice = finalPrice.multiply(new BigDecimal(quantity));

    // the final price is the product price * quantity

    if (finalPrice == null) {// pick it from the productPrice
        finalPrice = productPrice.getProductPriceAmount();
        finalPrice = finalPrice.multiply(new BigDecimal(quantity));
    }

    // this type of price needs an upfront payment
    BigDecimal otprice = orderSummary.getOneTimeSubTotal();
    if (otprice == null) {
        otprice = new BigDecimal(0);
    }

    otprice = otprice.add(finalPrice);
    orderSummary.setOneTimeSubTotal(otprice);

    ProductPriceSpecial pps = productPrice.getSpecial();

    // Build text
    StringBuffer notes = new StringBuffer();
    notes.append(quantity).append(" x ");
    notes.append(orderProduct.getProductName());
    notes.append(" ");
    if (!productPrice.isDefaultPrice()) {
        notes.append(
                CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency));
    } else {
        notes.append(CurrencyUtil.displayFormatedAmountWithCurrency(orderProduct.getProductPrice(), currency));
    }
    notes.append(" ");
    notes.append(this.getPriceSuffixText(currency, locale));

    if (pps != null) {
        if (pps.getProductPriceSpecialStartDate() != null && pps.getProductPriceSpecialEndDate() != null) {
            if (pps.getProductPriceSpecialStartDate().before(order.getDatePurchased())
                    && pps.getProductPriceSpecialEndDate().after(order.getDatePurchased())) {

                BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue());

                BigDecimal subTotal = originalPrice.multiply(new BigDecimal(orderProduct.getProductQuantity()));
                BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount()
                        .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                BigDecimal credit = subTotal.subtract(creditSubTotal);

                if (dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) {

                    discountPrice = productPrice.getProductPriceAmount().subtract(dPrice);

                    BigDecimal newPrice = orderProduct.getProductPrice();

                    if (!productPrice.isDefaultPrice()) {
                        newPrice = productPrice.getProductPriceAmount();
                    } else {
                        newPrice = newPrice.add(discountPrice);
                    }

                    StringBuffer spacialNote = new StringBuffer();
                    spacialNote.append("<font color=\"red\">[");
                    spacialNote.append(orderProduct.getProductName());
                    spacialNote.append(" ");
                    spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate"));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until"));

                    spacialNote.append(" ");
                    spacialNote.append(DateUtil.formatDate(pps.getProductPriceSpecialEndDate()));
                    spacialNote.append("]</font>");

                    OrderTotalLine line = new OrderTotalLine();
                    // BigDecimal credit = discountPrice;
                    line.setText(spacialNote.toString());
                    line.setCost(credit);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    orderSummary.addDueNowCredits(line);
                    orderSummary.addRecursiveCredits(line);

                    BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge();
                    oneTimeCredit = oneTimeCredit.add(credit);
                    orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit);

                }

            } else if (pps.getProductPriceSpecialDurationDays() > -1) {

                Date dt = new Date(new Date().getTime());

                int numDays = pps.getProductPriceSpecialDurationDays();
                Date purchased = order.getDatePurchased();
                Calendar c = Calendar.getInstance();
                c.setTime(dt);
                c.add(Calendar.DATE, numDays);

                BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue());

                if (dt.before(c.getTime())
                        && dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) {

                    discountPrice = productPrice.getProductPriceAmount().subtract(dPrice);

                    BigDecimal newPrice = orderProduct.getProductPrice();

                    BigDecimal subTotal = originalPrice
                            .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                    BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount()
                            .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                    BigDecimal credit = subTotal.subtract(creditSubTotal);

                    if (!productPrice.isDefaultPrice()) {
                        newPrice = productPrice.getProductPriceAmount();
                    } else {
                        newPrice = newPrice.add(discountPrice);
                    }

                    StringBuffer spacialNote = new StringBuffer();

                    spacialNote.append("<font color=\"red\">[");
                    spacialNote.append(orderProduct.getProductName());
                    spacialNote.append(" ");
                    spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate"));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until"));

                    spacialNote.append(" ");
                    spacialNote.append(DateUtil.formatDate(c.getTime()));
                    spacialNote.append("]</font>");

                    OrderTotalLine line = new OrderTotalLine();

                    line.setText(spacialNote.toString());
                    line.setCost(credit);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    orderSummary.addDueNowCredits(line);
                    if (numDays > 30) {
                        orderSummary.addRecursiveCredits(line);
                    }

                    BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge();
                    oneTimeCredit = oneTimeCredit.add(credit);
                    orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    // }

                }

            }

        }

    }

    BigDecimal newPrice = orderProduct.getProductPrice();
    if (!productPrice.isDefaultPrice()) {
        newPrice = productPrice.getProductPriceAmount();
    }

    newPrice = newPrice.multiply(new BigDecimal(quantity));

    // Recursive sub total
    BigDecimal rprice = orderSummary.getRecursiveSubTotal();
    if (rprice == null) {
        rprice = new BigDecimal(0);
    }

    // recursive always contain full price
    rprice = rprice.add(newPrice);
    orderSummary.setRecursiveSubTotal(rprice);

    // recursive price
    OrderTotalLine scl = new OrderTotalLine();
    scl.setText(notes.toString());
    scl.setCost(newPrice);
    scl.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(newPrice, currency));
    orderSummary.addRecursivePrice(scl);

    return orderSummary;

}

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private BigDecimal calculateDemandWithRecursiveAmount(final UsageSlab usageSlab,
        final MeteredRatesDetail meteredRatesDetail, final BigDecimal numberOfUnitsPerMonth) {
    BigDecimal totalAmount = BigDecimal.ZERO;
    BigDecimal amtValue;//from w w w .  j a v a  2  s .co  m
    BigDecimal amount1;
    BigDecimal amount2;
    if (meteredRatesDetail.getFlatAmount() != null && meteredRatesDetail.getFlatAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amtValue = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor())
                        .setScale(0, BigDecimal.ROUND_HALF_UP));
        totalAmount = BigDecimal.valueOf(meteredRatesDetail.getFlatAmount())
                .add(amtValue.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())));
    } else if (meteredRatesDetail.getRateAmount() != null && meteredRatesDetail.getRateAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amount1 = BigDecimal.valueOf(usageSlab.getFromVolume()).subtract(BigDecimal.ONE)
                .multiply(BigDecimal.valueOf(meteredRatesDetail.getRateAmount()));
        amount2 = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor()), 0,
                        BigDecimal.ROUND_HALF_UP);
        amtValue = amount2.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        totalAmount = amount1.add(amtValue);
    }
    return totalAmount;
}

From source file:org.openbravo.advpaymentmngt.actionHandler.ModifyPaymentPlanActionHandler.java

/**
 * Given an invoice payment plan line, this function returns the sum of all the amounts pending to
 * confirm (for example, in awaiting execution status) for that payment plan line
 * /*  w  ww.  j  ava 2  s.  c om*/
 */
private BigDecimal getPendingPSAmounts(FIN_PaymentSchedule invoicePS) {
    BigDecimal result = invoicePS.getAmount();
    for (FIN_PaymentScheduleDetail psd : invoicePS.getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
        if (!psd.isCanceled() && (psd.getPaymentDetails() != null)) {
            result = result.subtract(psd.getAmount());
        }
    }
    return result;
}

From source file:mx.edu.um.mateo.inventario.web.FacturaAlmacenController.java

@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
    log.debug("Mostrando factura {}", id);
    FacturaAlmacen factura = facturaDao.obtiene(id);
    switch (factura.getEstatus().getNombre()) {
    case Constantes.ABIERTA:
        modelo.addAttribute("puedeEditar", true);
        modelo.addAttribute("puedeEliminar", true);
        modelo.addAttribute("puedeCerrar", true);
        break;//  ww  w .jav  a 2  s  .co  m
    case Constantes.CERRADA:
        modelo.addAttribute("puedeCancelar", true);
        modelo.addAttribute("puedeReporte", true);
        break;
    }

    modelo.addAttribute("factura", factura);

    BigDecimal salidasTotal = BigDecimal.ZERO;
    BigDecimal salidasIva = BigDecimal.ZERO;
    for (Salida salida : factura.getSalidas()) {
        salidasTotal = salidasTotal.add(salida.getTotal());
        salidasIva = salidasIva.add(salida.getIva());
    }
    modelo.addAttribute("salidasTotal", salidasTotal);
    modelo.addAttribute("salidasIva", salidasIva);
    modelo.addAttribute("salidasSubtotal", salidasTotal.subtract(salidasIva));

    BigDecimal entradasTotal = BigDecimal.ZERO;
    BigDecimal entradasIva = BigDecimal.ZERO;
    for (Entrada entrada : factura.getEntradas()) {
        entradasTotal = entradasTotal.add(entrada.getTotal());
        entradasIva = entradasIva.add(entrada.getIva());
    }
    modelo.addAttribute("entradasTotal", entradasTotal);
    modelo.addAttribute("entradasIva", entradasIva);
    modelo.addAttribute("entradasSubtotal", entradasTotal.subtract(entradasIva));

    return "inventario/factura/ver";
}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

public BigDecimal adjustVaultIssuedAssets(final StellarAccountId stellarAccountId,
        final char[] stellarAccountPrivateKey, final StellarAccountId stellarVaultAccountId,
        final char[] stellarVaultAccountPrivateKey, final String assetCode, final BigDecimal amount)
        throws InvalidConfigurationException, StellarPaymentFailedException,
        StellarTrustlineAdjustmentFailedException {
    final BigDecimal currentVaultIssuedAssets = currencyTrustSize(stellarAccountId, assetCode,
            stellarVaultAccountId);/*w  w  w .j ava 2 s  .c om*/

    final BigDecimal adjustmentRequired = amount.subtract(currentVaultIssuedAssets);

    if (adjustmentRequired.compareTo(BigDecimal.ZERO) < 0) {
        final BigDecimal currentVaultIssuedAssetsHeldByTenant = getBalanceByIssuer(stellarAccountId, assetCode,
                stellarVaultAccountId);

        final BigDecimal adjustmentPossible = currentVaultIssuedAssetsHeldByTenant
                .min(adjustmentRequired.abs());

        final BigDecimal finalBalance = currentVaultIssuedAssets.subtract(adjustmentPossible);

        simplePay(stellarVaultAccountId, adjustmentPossible, assetCode, stellarVaultAccountId,
                stellarAccountPrivateKey);

        setTrustLineSize(stellarAccountPrivateKey, stellarVaultAccountId, assetCode, finalBalance);

        return finalBalance;
    } else if (adjustmentRequired.compareTo(BigDecimal.ZERO) > 0) {
        setTrustLineSize(stellarAccountPrivateKey, stellarVaultAccountId, assetCode, amount);

        simplePay(stellarAccountId, adjustmentRequired, assetCode, stellarVaultAccountId,
                stellarVaultAccountPrivateKey);

        return amount;
    } else {
        return currentVaultIssuedAssets;
    }
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxCarryOverServiceImpl.java

private BigDecimal getAccrualCategoryCarryOverAdjustment(String accrualCategory, String principalId,
        CalendarEntry calendarEntry, LocalDate asOfDate) {
    BigDecimal accrualCategoryCarryOverAdjustment = BigDecimal.ZERO;

    PrincipalHRAttributes principalCalendar = getPrincipalHRAttributesService()
            .getPrincipalCalendar(principalId, asOfDate);

    if (principalCalendar != null) {
        LeavePlan leavePlan = getLeavePlanService().getLeavePlan(principalCalendar.getLeavePlan(),
                principalCalendar.getEffectiveLocalDate());

        if (leavePlan != null) {
            AccrualCategory accrualCategoryObj = getAccrualCategoryService().getAccrualCategory(accrualCategory,
                    asOfDate);//from  w w w  . j a v  a  2  s . c o  m

            if (accrualCategoryObj != null) {
                AccrualCategoryRule accrualCategoryRule = getMaxCarryOverAccrualCategoryRule(accrualCategoryObj,
                        principalCalendar.getServiceLocalDate(), asOfDate);

                if (accrualCategoryRule != null) {
                    Long maxCarryOverLimitValue = getMaxCarryOverLimitValue(principalId, leavePlan,
                            accrualCategoryObj, accrualCategoryRule, asOfDate);

                    if (maxCarryOverLimitValue != null) {
                        BigDecimal accrualCategoryBalance = getAccrualCategoryBalance(principalId,
                                accrualCategoryObj, asOfDate);

                        BigDecimal maxCarryOverLimit = new BigDecimal(maxCarryOverLimitValue);
                        BigDecimal fteSum = getJobService().getFteSumForAllActiveLeaveEligibleJobs(principalId,
                                asOfDate);
                        BigDecimal maxCarryOver = maxCarryOverLimit.multiply(fteSum);

                        accrualCategoryCarryOverAdjustment = accrualCategoryBalance.subtract(maxCarryOver);
                    }
                }
            }
        }
    }

    return accrualCategoryCarryOverAdjustment;
}