Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TabularReport generateTabularReport(Properties ctx, String title, String subtitle, int account_id,
        Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    String sql = SalesAnalysisReportManager.getTabularDataSetSQL(ctx, account_id, fromDate, toDate, salesGroup);
    ArrayList<Object[]> tmpData = ReportManager.getReportData(ctx, sql, true);
    String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

    ArrayList<Object[]> reportData = new ArrayList<Object[]>();
    //copying data from tmpData to reportData

    NumberFormat formatter = new DecimalFormat("###,###,##0.00");

    Iterator<Object[]> iter = tmpData.iterator();

    Object[] data = null;/*from w  w w .j  ava 2  s.c  om*/
    Object[] headers = null;
    BigDecimal b, c = null;

    boolean isTaxDue = (account_id == Constants.TAX_DUE.intValue());
    boolean isTaxCredit = (account_id == Constants.TAX_CREDIT.intValue());

    if (isTaxCredit || isTaxDue) {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0] + "(" + currency + ")", });

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length == 1) {
                b = (BigDecimal) data[0];
                data[0] = formatter.format(b.doubleValue());
            }

            reportData.add(data);
        }
    } else {
        //copying header
        headers = iter.next();

        reportData.add(new Object[] { headers[0], headers[1], headers[2] + "(" + currency + ")", headers[3] });

        double totalAmt = 0.0d;
        BigDecimal totalQty = Env.ZERO;

        while (iter.hasNext()) {
            data = iter.next();

            if (data.length > 2) {
                b = (BigDecimal) data[2];
                c = (BigDecimal) data[3];

                data[2] = formatter.format(b.doubleValue());

                totalAmt += b.doubleValue();
                totalQty = totalQty.add(c);

            }

            reportData.add(data);
        }

        reportData.add(new Object[] { "Total", "", formatter.format(totalAmt) + "", totalQty + "" });

    }

    //style for table
    String tableStyle = "display";
    //style for columns        
    String[] styles = new String[] { "string", "date", "currency", "numeric" };

    if (isTaxCredit || isTaxDue) {
        styles = new String[] { "numeric" };
    }

    //constructing the table
    TabularReport tReport = new TabularReport(reportData);
    //tReport.setSortable(true);
    tReport.setHeaderStyle(styles);
    tReport.setStyle(tableStyle);
    tReport.setTitle(title);
    tReport.setSubtitle(subtitle);
    tReport.createReport();

    return tReport;
}

From source file:com.salesmanager.core.util.CheckoutUtil.java

/**
 * OrderProductAttribute is configured from javascript This code needs to
 * invoke catalog objects require getProductOptionValueId
 * //w w w  .ja v  a 2s  .com
 * @param attributes
 * @param lineId
 * @param currency
 * @param request
 * @return
 * @throws Exception
 */
public static OrderProduct addAttributesFromRawObjects(List<OrderProductAttribute> attributes, OrderProduct scp,
        String currency, HttpServletRequest request) throws Exception {

    Locale loc = request.getLocale();
    String lang = loc.getLanguage();

    CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);

    BigDecimal sumPrice = null;

    Locale locale = (Locale) request.getSession().getAttribute("WW_TRANS_I18N_LOCALE");
    if (locale == null)
        locale = request.getLocale();

    // get attributes for this product
    Collection productAttributes = cservice.getProductAttributes(scp.getProductId(), locale.getLanguage());
    Map mapAttributes = new HashMap();
    if (productAttributes != null) {

        Iterator i = productAttributes.iterator();
        while (i.hasNext()) {
            ProductAttribute p = (ProductAttribute) i.next();
            mapAttributes.put(p.getOptionValueId(), p);
        }

    }

    if (scp != null) {

        StringBuffer attributesLine = null;

        if (attributes != null) {
            attributesLine = new StringBuffer();
            int count = 0;
            Iterator i = attributes.iterator();
            while (i.hasNext()) {
                OrderProductAttribute opa = (OrderProductAttribute) i.next();
                String attrPriceText = opa.getPrice();
                BigDecimal attrPrice = null;
                if (attrPriceText != null) {
                    attrPrice = CurrencyUtil.validateCurrency(attrPriceText, currency);
                } else {
                    attrPrice = opa.getOptionValuePrice();
                }
                // get all information from the attribute
                ProductAttribute pa = (ProductAttribute) mapAttributes.get(opa.getProductOptionValueId());
                if (pa != null) {
                    if (attrPrice == null) {
                        attrPrice = pa.getOptionValuePrice();
                    }
                }
                if (attrPrice != null) {
                    opa.setOptionValuePrice(attrPrice);
                    opa.setPrice(CurrencyUtil.displayFormatedAmountNoCurrency(attrPrice, currency));
                    if (sumPrice == null) {
                        sumPrice = new BigDecimal(attrPrice.doubleValue()).setScale(2);
                    } else {

                        BigDecimal currentPrice = sumPrice;
                        sumPrice = currentPrice.add(attrPrice);
                    }
                }
                // opa.setOrderId(Long.parseLong(orderId));
                opa.setOrderProductId(scp.getProductId());
                opa.setProductAttributeIsFree(pa.isProductAttributeIsFree());

                opa.setProductOption("");
                if (StringUtils.isBlank(opa.getProductOptionValue())) {
                    opa.setProductOptionValue("");
                }

                ProductOption po = pa.getProductOption();
                Set poDescriptions = po.getDescriptions();
                if (poDescriptions != null) {
                    Iterator pi = poDescriptions.iterator();
                    while (pi.hasNext()) {
                        ProductOptionDescription pod = (ProductOptionDescription) pi.next();
                        if (pod.getId().getLanguageId() == LanguageUtil.getLanguageNumberCode(lang)) {
                            opa.setProductOption(pod.getProductOptionName());
                            break;
                        }
                    }
                }

                if (StringUtils.isBlank(opa.getProductOptionValue())) {
                    ProductOptionValue pov = pa.getProductOptionValue();
                    if (pov != null) {
                        Set povDescriptions = pov.getDescriptions();
                        if (povDescriptions != null) {
                            Iterator povi = povDescriptions.iterator();
                            while (povi.hasNext()) {
                                ProductOptionValueDescription povd = (ProductOptionValueDescription) povi
                                        .next();
                                if (povd.getId().getLanguageId() == LanguageUtil.getLanguageNumberCode(lang)) {
                                    opa.setProductOptionValue(povd.getProductOptionValueName());
                                    break;
                                }
                            }
                        }
                    }
                }
                opa.setProductAttributeWeight(pa.getProductAttributeWeight());
                if (count == 0) {
                    attributesLine.append("[ ");
                }
                attributesLine.append(opa.getProductOption()).append(" -> ")
                        .append(opa.getProductOptionValue());
                if (count + 1 == attributes.size()) {
                    attributesLine.append("]");
                } else {
                    attributesLine.append(", ");
                }
                count++;
            }
        }

        // add attribute price to productprice
        if (sumPrice != null) {
            // sumPrice = sumPrice.multiply(new
            // BigDecimal(scp.getProductQuantity()));

            // get product price
            BigDecimal productPrice = scp.getProductPrice();
            productPrice = productPrice.add(sumPrice);

            // added
            scp.setProductPrice(productPrice);

            // BigDecimal finalPrice = scp.getFinalPrice();
            BigDecimal finalPrice = productPrice.multiply(new BigDecimal(scp.getProductQuantity()));
            // finalPrice = finalPrice.add(sumPrice);
            // BigDecimal cost = scp.get

            scp.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(productPrice, currency));
            scp.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(finalPrice, currency));
        }

        if (attributesLine != null) {
            scp.setAttributesLine(attributesLine.toString());
        }

        Set attributesSet = new HashSet(attributes);

        scp.setOrderattributes(attributesSet);

    }

    return scp;
}

From source file:adalid.commons.util.ObjUtils.java

public static BigDecimal sum(Object... objects) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal augend;//from  w  w w  .ja  v a 2s . co  m
    for (Object obj : objects) {
        augend = NumUtils.numberToBigDecimal(obj);
        if (augend == null) {
            return null;
        }
        result.add(augend);
    }
    return result;
}

From source file:com.salesmanager.core.util.CheckoutUtil.java

/**
 * OrderProductAttribute is configured from javascript This code needs to
 * invoke catalog objects because it requires getProductOptionValueId, will
 * not change any price Add attributes to product, add attribute offset
 * price to original product price//from www . j a  v  a  2 s.  c o m
 * 
 * @param attributes
 * @param lineId
 * @param currency
 * @param request
 * @return
 * @throws Exception
 */
public static OrderProduct addAttributesFromRawObjects(List<OrderProductAttribute> attributes, long productId,
        String lineId, String currency, HttpServletRequest request) throws Exception {

    Locale loc = request.getLocale();
    String lang = loc.getLanguage();

    HttpSession session = request.getSession();

    Map cartLines = SessionUtil.getOrderProducts(request);

    if (cartLines == null) {
        throw new Exception("No OrderProduct exixt yet, cannot assign attributes");
    }

    OrderProduct scp = (OrderProduct) cartLines.get(lineId);

    if (scp == null) {
        throw new Exception("No OrderProduct exixt for lineId " + lineId);
    }

    CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);

    BigDecimal sumPrice = null;

    // make sure OrderProduct and productId match
    if (scp.getProductId() == productId) {

        Locale locale = (Locale) request.getSession().getAttribute("WW_TRANS_I18N_LOCALE");
        if (locale == null)
            locale = request.getLocale();

        // get attributes for this product
        Collection productAttributes = cservice.getProductAttributes(productId, locale.getLanguage());
        Map mapAttributes = new HashMap();
        if (productAttributes != null) {

            Iterator i = productAttributes.iterator();
            while (i.hasNext()) {
                ProductAttribute p = (ProductAttribute) i.next();
                mapAttributes.put(p.getOptionValueId(), p);
            }

        }

        if (scp != null) {

            StringBuffer attributesLine = null;

            if (attributes != null) {
                attributesLine = new StringBuffer();
                int count = 0;
                Iterator i = attributes.iterator();
                while (i.hasNext()) {
                    OrderProductAttribute opa = (OrderProductAttribute) i.next();
                    String attrPriceText = opa.getPrice();
                    BigDecimal attrPrice = null;
                    if (attrPriceText != null) {
                        attrPrice = CurrencyUtil.validateCurrency(attrPriceText, currency);
                    } else {
                        attrPrice = opa.getOptionValuePrice();
                    }
                    // get all information from the attribute
                    ProductAttribute pa = (ProductAttribute) mapAttributes.get(opa.getProductOptionValueId());
                    if (pa != null) {
                        if (attrPrice == null) {
                            attrPrice = pa.getOptionValuePrice();
                        }
                    }
                    if (attrPrice != null) {
                        opa.setOptionValuePrice(attrPrice);
                        opa.setPrice(CurrencyUtil.displayFormatedAmountNoCurrency(attrPrice, currency));
                        if (sumPrice == null) {
                            sumPrice = new BigDecimal(attrPrice.doubleValue()).setScale(2);
                        } else {
                            // double pr = sumPrice.doubleValue() +
                            // attrPrice.doubleValue();
                            // sumPrice = new
                            // BigDecimal(sumPrice.doubleValue() +
                            // attrPrice.doubleValue());
                            BigDecimal currentPrice = sumPrice;
                            sumPrice = currentPrice.add(attrPrice);
                        }
                    }
                    // opa.setOrderId(Long.parseLong(orderId));
                    opa.setOrderProductId(productId);
                    opa.setProductAttributeIsFree(pa.isProductAttributeIsFree());

                    opa.setProductOption("");
                    if (StringUtils.isBlank(opa.getProductOptionValue())) {
                        opa.setProductOptionValue("");
                    }

                    ProductOption po = pa.getProductOption();
                    Set poDescriptions = po.getDescriptions();
                    if (poDescriptions != null) {
                        Iterator pi = poDescriptions.iterator();
                        while (pi.hasNext()) {
                            ProductOptionDescription pod = (ProductOptionDescription) pi.next();
                            if (pod.getId().getLanguageId() == LanguageUtil.getLanguageNumberCode(lang)) {
                                opa.setProductOption(pod.getProductOptionName());
                                break;
                            }
                        }
                    }

                    if (StringUtils.isBlank(opa.getProductOptionValue())) {
                        ProductOptionValue pov = pa.getProductOptionValue();
                        if (pov != null) {
                            Set povDescriptions = pov.getDescriptions();
                            if (povDescriptions != null) {
                                Iterator povi = povDescriptions.iterator();
                                while (povi.hasNext()) {
                                    ProductOptionValueDescription povd = (ProductOptionValueDescription) povi
                                            .next();
                                    if (povd.getId().getLanguageId() == LanguageUtil
                                            .getLanguageNumberCode(lang)) {
                                        opa.setProductOptionValue(povd.getProductOptionValueName());
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    opa.setProductAttributeWeight(pa.getProductAttributeWeight());
                    if (count == 0) {
                        attributesLine.append("[ ");
                    }
                    attributesLine.append(opa.getProductOption()).append(" -> ")
                            .append(opa.getProductOptionValue());
                    if (count + 1 == attributes.size()) {
                        attributesLine.append("]");
                    } else {
                        attributesLine.append(", ");
                    }
                    count++;
                }
            }

            // add attribute price to productprice
            if (sumPrice != null) {
                // sumPrice = sumPrice.multiply(new
                // BigDecimal(scp.getProductQuantity()));

                scp.setAttributeAdditionalCost(sumPrice);// add additional
                // attribute
                // price

                // get product price
                BigDecimal productPrice = scp.getProductPrice();
                productPrice = productPrice.add(sumPrice);

                // added
                scp.setProductPrice(productPrice);

                // BigDecimal finalPrice = scp.getFinalPrice();
                BigDecimal finalPrice = productPrice.multiply(new BigDecimal(scp.getProductQuantity()));
                // finalPrice = finalPrice.add(sumPrice);
                // BigDecimal cost = scp.get

                scp.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(productPrice, currency));
                scp.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(finalPrice, currency));
            }

            if (attributesLine != null) {
                scp.setAttributesLine(attributesLine.toString());
            }

            Set attributesSet = new HashSet(attributes);

            scp.setOrderattributes(attributesSet);

        }

    }

    return scp;
}

From source file:at.illecker.hama.hybrid.examples.summation.SummationBSP.java

static BigDecimal writeSummationInputFile(FileSystem fs, Path dir, int fileCount) throws IOException {

    BigDecimal sum = new BigDecimal(0);
    Random rand = new Random();
    double rangeMin = 0;
    double rangeMax = 100;

    for (int i = 0; i < fileCount; i++) {
        DataOutputStream out = fs.create(new Path(dir, "part" + i));

        // loop between 50 and 149 times
        for (int j = 0; j < rand.nextInt(100) + 50; j++) {
            // generate key value pair inputs
            double randomValue = rangeMin + (rangeMax - rangeMin) * rand.nextDouble();

            String truncatedValue = new BigDecimal(randomValue)
                    .setScale(DOUBLE_PRECISION, BigDecimal.ROUND_DOWN).toString();

            String line = "key" + (j + 1) + "\t" + truncatedValue + "\n";
            out.writeBytes(line);/*from ww w  . j  a  v a 2 s .c om*/

            sum = sum.add(new BigDecimal(truncatedValue));
            LOG.debug("input[" + j + "]: '" + line + "' sum: " + sum.toString());
        }
        out.close();
    }
    return sum;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.PHS398ChecklistV1_3Generator.java

private static IncomeBudgetPeriod[] getIncomeBudgetPeriod(
        final List<? extends BudgetProjectIncomeContract> projectIncomes) {
    //TreeMap Used to maintain the order of the Budget periods.
    Map<Integer, IncomeBudgetPeriod> incomeBudgetPeriodMap = new TreeMap<>();
    BigDecimal anticipatedAmount;
    for (BudgetProjectIncomeContract projectIncome : projectIncomes) {

        Integer budgetPeriodNumber = projectIncome.getBudgetPeriodNumber();
        IncomeBudgetPeriod incomeBudgPeriod = incomeBudgetPeriodMap.get(budgetPeriodNumber);
        if (incomeBudgPeriod == null) {
            incomeBudgPeriod = IncomeBudgetPeriod.Factory.newInstance();
            incomeBudgPeriod.setBudgetPeriod(budgetPeriodNumber);
            anticipatedAmount = BigDecimal.ZERO;
        } else {//w  w  w . j a v  a2s  .com
            anticipatedAmount = incomeBudgPeriod.getAnticipatedAmount();
        }
        anticipatedAmount = anticipatedAmount.add(projectIncome.getProjectIncome().bigDecimalValue());
        incomeBudgPeriod.setAnticipatedAmount(anticipatedAmount);
        String description = getProjectIncomeDescription(projectIncome);
        if (description != null) {
            if (incomeBudgPeriod.getSource() != null) {
                incomeBudgPeriod.setSource(incomeBudgPeriod.getSource() + ";" + description);
            } else {
                incomeBudgPeriod.setSource(description);
            }
        }
        incomeBudgetPeriodMap.put(budgetPeriodNumber, incomeBudgPeriod);
    }
    Collection<IncomeBudgetPeriod> incomeBudgetPeriodCollection = incomeBudgetPeriodMap.values();
    return incomeBudgetPeriodCollection.toArray(new IncomeBudgetPeriod[0]);
}

From source file:Main.java

/**
 * Compute the integral root of x to a given scale, x >= 0.
 * Use Newton's algorithm.//from w  w w .  java2s  .  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.csware.ee.utils.Tools.java

public static double add(double v1, double v2)

{

    BigDecimal b1 = new BigDecimal(Double.toString(v1));

    BigDecimal b2 = new BigDecimal(Double.toString(v2));

    return b1.add(b2).doubleValue();

}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.PHS398CoverPageSupplement_3_0V3_0Generator.java

private static IncomeBudgetPeriod[] getIncomeBudgetPeriod(
        final List<? extends BudgetProjectIncomeContract> projectIncomes) {
    //TreeMap Used to maintain the order of the Budget periods.
    Map<Integer, IncomeBudgetPeriod> incomeBudgetPeriodMap = new TreeMap<>();
    BigDecimal anticipatedAmount;
    for (BudgetProjectIncomeContract projectIncome : projectIncomes) {

        Integer budgetPeriodNumber = projectIncome.getBudgetPeriodNumber();
        IncomeBudgetPeriod incomeBudgPeriod = incomeBudgetPeriodMap.get(budgetPeriodNumber);
        if (incomeBudgPeriod == null) {
            incomeBudgPeriod = IncomeBudgetPeriod.Factory.newInstance();
            incomeBudgPeriod.setBudgetPeriod(budgetPeriodNumber);
            anticipatedAmount = BigDecimal.ZERO;
        } else {//w  w w .j a v a 2s  .co  m
            anticipatedAmount = incomeBudgPeriod.getAnticipatedAmount();
        }
        anticipatedAmount = anticipatedAmount.add(projectIncome.getProjectIncome().bigDecimalValue());
        incomeBudgPeriod.setAnticipatedAmount(anticipatedAmount);
        String description = getProjectIncomeDescription(projectIncome);
        if (description != null) {
            if (incomeBudgPeriod.getSource() != null) {
                incomeBudgPeriod.setSource(incomeBudgPeriod.getSource() + ";" + description);
            } else {
                incomeBudgPeriod.setSource(description);
            }
        }
        incomeBudgetPeriodMap.put(budgetPeriodNumber, incomeBudgPeriod);
    }
    return incomeBudgetPeriodMap.values().stream().toArray(IncomeBudgetPeriod[]::new);
}

From source file:ru.transaction.util.TransactionSumCalculatorRecursive.java

@Override
public BigDecimal calculateSum(BigDecimal currentSum, TransactionEntity transaction) {
    currentSum = currentSum.add(new BigDecimal(transaction.getAmount()));
    Collection<TransactionEntity> childTransactions = transactionRepository.findByParentId(transaction.getId());
    for (TransactionEntity childTransaction : childTransactions) {
        currentSum = calculateSum(currentSum, childTransaction);
    }// ww  w .  j  a  v a 2  s  . c  o m
    return currentSum;
}