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:org.projectforge.business.fibu.OrderExport.java

private void addOrderMapping(final PropertyMapping mapping, final AuftragDO order) {
    auftragDao.calculateInvoicedSum(order);
    mapping.add(OrderCol.NUMMER, order.getNummer());
    mapping.add(OrderCol.NUMBER_OF_POSITIONS,
            "#" + (order.getPositionen() != null ? order.getPositionen().size() : "0"));
    mapping.add(OrderCol.DATE, order.getAngebotsDatum());
    mapping.add(OrderCol.ORDER_DATE, order.getBeauftragungsDatum());
    mapping.add(OrderCol.STATUS,//w  w w.ja va  2  s.  co  m
            order.getAuftragsStatus() != null
                    ? ThreadLocalUserContext.getLocalizedString(order.getAuftragsStatus().getI18nKey())
                    : "");
    mapping.add(OrderCol.STATUS_COMMENT, order.getStatusBeschreibung());
    mapping.add(OrderCol.PROJECT, order.getProjektAsString());
    final ProjektDO project = order.getProjekt();
    final String projectCustomer = KundeFormatter
            .formatKundeAsString(project != null ? project.getKunde() : null, order.getKundeText());
    mapping.add(OrderCol.PROJECT_CUSTOMER, projectCustomer);
    mapping.add(OrderCol.TITLE, order.getTitel());
    final BigDecimal netSum = order.getNettoSumme() != null ? order.getNettoSumme() : BigDecimal.ZERO;
    final BigDecimal invoicedSum = order.getFakturiertSum() != null ? order.getFakturiertSum()
            : BigDecimal.ZERO;
    final BigDecimal toBeInvoicedSum = netSum.subtract(invoicedSum);
    mapping.add(OrderCol.NETSUM, netSum);
    addCurrency(mapping, OrderCol.INVOICED, invoicedSum);
    addCurrency(mapping, OrderCol.TO_BE_INVOICED, toBeInvoicedSum);
    mapping.add(OrderCol.COMPLETELY_INVOICED, order.isVollstaendigFakturiert() == true ? "x" : "");
    final Set<RechnungsPositionVO> invoicePositions = rechnungCache
            .getRechnungsPositionVOSetByAuftragId(order.getId());
    mapping.add(OrderCol.INVOICES, getInvoices(invoicePositions));
    mapping.add(OrderCol.PERIOD_OF_PERFORMANCE_BEGIN, order.getPeriodOfPerformanceBegin());
    mapping.add(OrderCol.PERIOD_OF_PERFORMANCE_END, order.getPeriodOfPerformanceEnd());
    final PFUserDO contactPerson = TenantRegistryMap.getInstance().getTenantRegistry().getUserGroupCache()
            .getUser(order.getContactPersonId());
    mapping.add(OrderCol.CONTACT_PERSON, contactPerson != null ? contactPerson.getFullname() : "");
    mapping.add(OrderCol.REFERENCE, order.getReferenz());
    mapping.add(OrderCol.COMMENT, order.getBemerkung());
}

From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java

/**
 * Gets the JS for fill up./* w  ww . j av a  2s. com*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fill up
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FillUp(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0) {
                            final RateInfo revRateInfo = rateInfo.reverse();
                            final BigDecimal target = Currency.convertToCurrency(_parameter, targetRate,
                                    revRateInfo, null, rateInfo.getCurrencyInstance())
                                    .setScale(2, RoundingMode.HALF_UP);

                            final String amountStr = formater.format(target);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amount_" + postfix, amountStr))
                                    .append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amount_" + postfix, i, amountStr);
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:org.efaps.esjp.accounting.transaction.Calculation_Base.java

/**
 * Gets the JS 4 fit exchange rate.//from  www  .  ja  va  2  s.c om
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fit ex rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FitExRate(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0
                                && BigDecimal.ZERO.compareTo(currAmount) < 0) {
                            final BigDecimal rate;
                            if (rateInfo.isInvert()) {
                                rate = targetRate.setScale(8, RoundingMode.HALF_UP).divide(currAmount,
                                        RoundingMode.HALF_UP);
                            } else {
                                rate = currAmount.setScale(8, RoundingMode.HALF_UP).divide(targetRate,
                                        RoundingMode.HALF_UP);
                            }

                            final String rateStr = NumberFormatter.get().getFormatter(null, 8).format(rate);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr))
                                    .append(getSetFieldValue(i, "rate_" + postfix, rateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);
                            ParameterUtil.setParameterValue(_parameterClone, "rate_" + postfix, i, rateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java

/**
 * Method used to update the credit used when the user doing invoice processing or payment
 * processing// w  w w. j a v a 2  s  .c om
 * 
 * @param amount
 *          Payment amount
 */
private static void updateCustomerCredit(BusinessPartner businessPartner, BigDecimal amount, boolean add) {
    BigDecimal creditUsed = businessPartner.getCreditUsed();
    if (add) {
        creditUsed = creditUsed.add(amount);
    } else {
        creditUsed = creditUsed.subtract(amount);
    }
    businessPartner.setCreditUsed(creditUsed);
    OBDal.getInstance().save(businessPartner);
    // OBDal.getInstance().flush();
}

From source file:Main.java

/**
 * Compute the integral root of x to a given scale, x >= 0.
 * Use Newton's algorithm.//from  ww  w  .  j a v  a  2 s.c o m
 * @param x the value of x
 * @param index the integral root value
 * @param scale the desired scale of the result
 * @return the result value
 */
public static BigDecimal intRoot(BigDecimal x, long index, int scale) {
    // Check that x >= 0.
    if (x.signum() < 0) {
        throw new IllegalArgumentException("x < 0");
    }

    int sp1 = scale + 1;
    BigDecimal n = x;
    BigDecimal i = BigDecimal.valueOf(index);
    BigDecimal im1 = BigDecimal.valueOf(index - 1);
    BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1);
    BigDecimal xPrev;

    // The initial approximation is x/index.
    x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do {
        // x^(index-1)
        BigDecimal xToIm1 = intPower(x, index - 1, sp1);

        // x^index
        BigDecimal xToI = x.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // n + (index-1)*(x^index)
        BigDecimal numerator = n.add(im1.multiply(xToI)).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // (index*(x^(index-1))
        BigDecimal denominator = i.multiply(xToIm1).setScale(sp1, BigDecimal.ROUND_HALF_EVEN);

        // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
        xPrev = x;
        x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN);

        Thread.yield();
    } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);

    return x;
}

From source file:org.egov.services.budget.BudgetAppropriationService.java

private void populateDataForBill(final EgBillregister bill, final CFinancialYear financialYear,
        final EgBilldetails detail, final BudgetReportEntry budgetReportEntry, final CChartOfAccounts coa) {
    final CFunction function = getFunction(detail);
    final Map<String, Object> budgetDataMap = getRequiredBudgetDataForBill(bill, financialYear, function, coa);
    budgetReportEntry.setFunctionName(function.getName());
    budgetReportEntry.setGlCode(coa.getGlcode());
    budgetReportEntry.setFinancialYear(financialYear.getFinYearRange());
    BigDecimal budgetedAmtForYear = BigDecimal.ZERO;
    try {//w  w  w .j  av  a2 s  .  co m
        budgetedAmtForYear = budgetDetailsDAO.getBudgetedAmtForYear(budgetDataMap);
    } catch (final ValidationException e) {
        throw e;
    }
    budgetReportEntry.setBudgetedAmtForYear(budgetedAmtForYear);
    populateBudgetAppNumber(bill, budgetReportEntry);
    final BigDecimal billAmount = getBillAmount(detail);
    BigDecimal soFarAppropriated = BigDecimal.ZERO;
    soFarAppropriated = getSoFarAppropriated(budgetDataMap, billAmount);
    budgetReportEntry.setAccountCode(coa.getGlcode());
    budgetReportEntry.setSoFarAppropriated(soFarAppropriated);
    final BigDecimal balance = budgetReportEntry.getBudgetedAmtForYear()
            .subtract(budgetReportEntry.getSoFarAppropriated());
    budgetReportEntry.setBalance(balance);
    budgetReportEntry.setCumilativeIncludingCurrentBill(soFarAppropriated.add(billAmount));
    budgetReportEntry.setCurrentBalanceAvailable(balance.subtract(billAmount));
    budgetReportEntry.setCurrentBillAmount(billAmount);
}

From source file:org.egov.services.budget.BudgetAppropriationService.java

private void populateDataForVoucher(final CVoucherHeader voucher, final CFinancialYear financialYear,
        final CGeneralLedger detail, final BudgetReportEntry budgetReportEntry) {
    final CFunction function = getFunctionForGl(detail);
    final CChartOfAccounts coa = detail.getGlcodeId();
    final Map<String, Object> budgetDataMap = getRequiredBudgetDataForVoucher(voucher, financialYear, function,
            coa);//w  w  w .ja  v  a 2s.  c  o  m
    budgetReportEntry.setFunctionName(function.getName());
    budgetReportEntry.setGlCode(coa.getGlcode());
    budgetReportEntry.setFinancialYear(financialYear.getFinYearRange());
    BigDecimal budgetedAmtForYear = BigDecimal.ZERO;
    try {
        budgetedAmtForYear = budgetDetailsDAO.getBudgetedAmtForYear(budgetDataMap);
    } catch (final ValidationException e) {
        throw e;
    }
    budgetReportEntry.setBudgetedAmtForYear(budgetedAmtForYear);
    populateBudgetAppNumberForVoucher(voucher, budgetReportEntry);
    final BigDecimal billAmount = getVoucherAmount(detail);
    BigDecimal soFarAppropriated = BigDecimal.ZERO;
    soFarAppropriated = getSoFarAppropriated(budgetDataMap, billAmount);
    budgetReportEntry.setAccountCode(coa.getGlcode());
    budgetReportEntry.setSoFarAppropriated(soFarAppropriated);
    final BigDecimal balance = budgetReportEntry.getBudgetedAmtForYear()
            .subtract(budgetReportEntry.getSoFarAppropriated());
    budgetReportEntry.setBalance(balance);
    budgetReportEntry.setCumilativeIncludingCurrentBill(soFarAppropriated.add(billAmount));
    budgetReportEntry.setCurrentBalanceAvailable(balance.subtract(billAmount));
    budgetReportEntry.setCurrentBillAmount(billAmount);
}

From source file:org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.java

private BigDecimal getAvancement(SQLRowAccessor r) {
    Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("ECHEANCE_CLIENT"));
    long totalEch = 0;

    for (SQLRowAccessor row : rows) {
        if (!row.getBoolean("REGLE") && !row.getBoolean("REG_COMPTA")) {
            totalEch += row.getLong("MONTANT");
        }/*w  ww  .  ja v a  2s . com*/
    }

    SQLRowAccessor avoir = r.getForeign("ID_AVOIR_CLIENT");
    BigDecimal avoirTTC = BigDecimal.ZERO;
    if (avoir != null && !avoir.isUndefined()) {
        avoirTTC = new BigDecimal(avoir.getLong("MONTANT_TTC"));
    }

    final BigDecimal totalAregler = new BigDecimal(r.getLong("T_TTC")).subtract(avoirTTC);
    if (totalAregler.signum() > 0 && totalEch > 0) {
        return totalAregler.subtract(new BigDecimal(totalEch)).divide(totalAregler, MathContext.DECIMAL128)
                .movePointRight(2).setScale(2, RoundingMode.HALF_UP);
    } else {
        return BigDecimal.ONE.movePointRight(2);
    }
}

From source file:ddf.catalog.validation.impl.validator.RangeValidator.java

/**
 * Creates a {@code RangeValidator} with an <strong>inclusive</strong> range and the provided
 * epsilon./*from w w  w.ja  v a 2  s.  c o  m*/
 * <p>
 * Uses the provided epsilon on both sides of the range to account for floating point
 * representation inaccuracies, so the range is really [min - epsilon, max + epsilon].
 *
 * @param min     the minimum allowable value (inclusive), cannot be null
 * @param max     the maximum allowable value (inclusive), cannot be null and must be greater
 *                than {@code min}
 * @param epsilon the epsilon value, cannot be null and must be positive
 * @throws IllegalArgumentException if {@code max} is not greater than {@code min},
 *                                  {@code epsilon} is not positive, or if any argument is null
 */
public RangeValidator(final BigDecimal min, final BigDecimal max, final BigDecimal epsilon) {
    Preconditions.checkArgument(min != null, "The minimum cannot be null.");
    Preconditions.checkArgument(max != null, "The maximum cannot be null.");
    Preconditions.checkArgument(epsilon != null, "The epsilon cannot be null.");
    Preconditions.checkArgument(min.compareTo(max) == -1, "The maximum must be greater than the minimum.");
    Preconditions.checkArgument(epsilon.compareTo(BigDecimal.ZERO) == 1, "The epsilon must be greater than 0.");

    this.min = min.subtract(epsilon);
    this.max = max.add(epsilon);
}

From source file:org.jlgranda.fede.ui.util.UI.java

/**
 * Imprime emoticons para ocultar la cantidad factor
 * @param total/*from  w  ww. ja va  2s . c  o m*/
 * @param gap
 * @return 
 */
public String calculeEmoticon(BigDecimal total, int gap) {
    String emoticon = "<i class=\"fa  fa-flag-o\"></i>";
    int half_gap = gap / 2;
    if (total.compareTo(BigDecimal.valueOf(gap)) > 0) {
        int factor;
        factor = total.intValue() / gap;
        emoticon = "";
        for (int i = 0; i < factor; i++) {
            emoticon = emoticon + "<i class=\"fa fa-flag\"></i>";
        }

        BigDecimal excedente = total.subtract(new BigDecimal(factor * gap));
        if (excedente.compareTo(BigDecimal.valueOf(half_gap)) > 0) {
            emoticon = emoticon + "<i class=\"fa fa-flag-checkered\"></i>";
        } else {
            emoticon = emoticon + "<i class=\"fa fa-flag-o\"></i>";
        }
    } else if (total.compareTo(BigDecimal.valueOf(half_gap)) > 0) {
        emoticon = "<i class=\"fa fa-flag-checkered\"></i>";
    }
    return emoticon;
}