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:com.spaceprogram.simplejpa.util.AmazonSimpleDBUtil.java

public static String encodeRealNumberRange(BigDecimal number, int maxDigitsLeft, int maxDigitsRight,
        BigDecimal offsetValue) {
    BigDecimal shiftMultiplier = new BigDecimal(Math.pow(10, maxDigitsRight));
    //        System.out.println("shiftMultiplier=" + shiftMultiplier);
    BigDecimal shiftedNumber = number.multiply(shiftMultiplier);
    //        System.out.println("shiftedNumber=" + shiftedNumber);
    shiftedNumber = shiftedNumber.setScale(0, BigDecimal.ROUND_HALF_UP);
    //        System.out.println("shiftedNumber rounded=" + shiftedNumber);
    BigDecimal shiftedOffset = offsetValue.multiply(shiftMultiplier);
    //        System.out.println("shiftedOffset=" + shiftedOffset);
    BigDecimal offsetNumber = shiftedNumber.add(shiftedOffset);
    //        System.out.println("offsetNumber=" + offsetNumber);
    String longString = offsetNumber.toString();
    //        System.out.println("shifted string=" + longString);
    int numBeforeDecimal = longString.length();
    int numZeroes = maxDigitsLeft + maxDigitsRight - numBeforeDecimal;
    StringBuffer strBuffer = new StringBuffer(numZeroes + longString.length());
    for (int i = 0; i < numZeroes; i++) {
        strBuffer.insert(i, '0');
    }//from  ww w .  j  av  a2s  .  co  m
    strBuffer.append(longString);
    return strBuffer.toString();
}

From source file:jgnash.ui.report.compiled.MonthlyAccountBalanceChart.java

private static BigDecimal calculateTotal(final LocalDate start, final LocalDate end, final Account account,
        final CurrencyNode baseCurrency) {
    BigDecimal amount;
    AccountType type = account.getAccountType();

    // get the amount for the account                
    amount = AccountBalanceDisplayManager.convertToSelectedBalanceMode(type,
            account.getBalance(start, end, baseCurrency));

    // add the amount of every sub accounts
    for (final Account child : account.getChildren(Comparators.getAccountByCode())) {
        amount = amount.add(calculateTotal(start, end, child, baseCurrency));
    }/*  w  w  w.  j a v a 2s  . c  o m*/
    return amount;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

public static String generateNextPartitionOffset(TableContext tableContext, String column, String offset) {
    final String partitionSize = tableContext.getOffsetColumnToPartitionOffsetAdjustments().get(column);
    switch (tableContext.getOffsetColumnToType().get(column)) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        final int int1 = Integer.parseInt(offset);
        final int int2 = Integer.parseInt(partitionSize);
        return String.valueOf(int1 + int2);
    case Types.TIMESTAMP:
        final Timestamp timestamp1 = getTimestampForOffsetValue(offset);
        final long timestampAdj = Long.parseLong(partitionSize);
        final Timestamp timestamp2 = Timestamp.from(timestamp1.toInstant().plusMillis(timestampAdj));
        return getOffsetValueForTimestamp(timestamp2);
    case Types.BIGINT:
        // TIME, DATE are represented as long (epoch)
    case Types.TIME:
    case Types.DATE:
        final long long1 = Long.parseLong(offset);
        final long long2 = Long.parseLong(partitionSize);
        return String.valueOf(long1 + long2);
    case Types.FLOAT:
    case Types.REAL:
        final float float1 = Float.parseFloat(offset);
        final float float2 = Float.parseFloat(partitionSize);
        return String.valueOf(float1 + float2);
    case Types.DOUBLE:
        final double double1 = Double.parseDouble(offset);
        final double double2 = Double.parseDouble(partitionSize);
        return String.valueOf(double1 + double2);
    case Types.NUMERIC:
    case Types.DECIMAL:
        final BigDecimal decimal1 = new BigDecimal(offset);
        final BigDecimal decimal2 = new BigDecimal(partitionSize);
        return decimal1.add(decimal2).toString();
    }/*from   w  ww .  ja v  a 2  s  .  co m*/
    return null;
}

From source file:com.sunchenbin.store.feilong.core.lang.NumberUtil.java

/**
 * ?(null).//from  ww w.j av  a 2s  .  c om
 *
 * @param numbers
 *            the numbers
 * @return the  value
 * @since 1.2.1
 */
public static BigDecimal getAddValue(Number... numbers) {
    BigDecimal returnValue = BigDecimal.ZERO;
    for (Number number : numbers) {
        if (Validator.isNotNullOrEmpty(number)) {
            BigDecimal bigDecimal = ConvertUtil.toBigDecimal(number);
            returnValue = returnValue.add(bigDecimal);
        }
    }
    return returnValue;
}

From source file:jgnash.ui.report.compiled.MonthlyAccountBalanceChartCompare.java

private static BigDecimal calculateTotal(final LocalDate start, final LocalDate end, final Account account,
        boolean recursive, final CurrencyNode baseCurrency) {
    BigDecimal amount;
    AccountType type = account.getAccountType();

    // get the amount for the account                
    amount = AccountBalanceDisplayManager.convertToSelectedBalanceMode(type,
            account.getBalance(start, end, baseCurrency));

    if (recursive) {
        // add the amount of every sub accounts
        for (final Account child : account.getChildren(Comparators.getAccountByCode())) {
            amount = amount.add(calculateTotal(start, end, child, true, baseCurrency));
        }/*from  w  w  w.  j  a v a  2s . com*/
    }

    return amount;
}

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

public static BigDecimal xPlusY(Object x, Object y) {
    BigDecimal bx = NumUtils.numberToBigDecimal(x);
    BigDecimal by = bx == null ? null : NumUtils.numberToBigDecimal(y);
    return bx == null || by == null ? null : bx.add(by);
}

From source file:com.xumpy.timesheets.services.TickedJobsDetailSrv.java

public static TickedJobsDetail calculate(List<? extends TickedJobs> tickedJobs) {
    TickedJobsDetail tickedJobsDetail = new TickedJobsDetail();
    tickedJobsDetail.setTickedJobs(tickedJobs);

    if (tickedJobs.size() > 0) {
        tickedJobs = sortTickedJobs(tickedJobs);

        Date startCounterWork = null;
        Date startCounterPause = null;

        BigDecimal workedMinutes = new BigDecimal(0);
        BigDecimal pausedMinutes = new BigDecimal(0);

        for (int i = 0; i < tickedJobs.size(); i++) {
            if (i % 2 == 0) {
                if (!tickedJobs.get(i).isStarted()) {
                    tickedJobsDetail.setActualPause(new BigDecimal(-1));
                    tickedJobsDetail.setActualWorked(new BigDecimal(-1));
                    break;
                } else {
                    if (startCounterPause != null) {
                        Minutes minutes = Minutes.minutesBetween(new DateTime(startCounterPause),
                                new DateTime(tickedJobs.get(i).getTicked()));

                        pausedMinutes = pausedMinutes.add(new BigDecimal(minutes.getMinutes()));
                    }/*from   ww w . ja v a2  s.  co m*/
                    startCounterWork = tickedJobs.get(i).getTicked();
                }
            } else {
                if (tickedJobs.get(i).isStarted()) {
                    tickedJobsDetail.setActualPause(new BigDecimal(-1));
                    tickedJobsDetail.setActualWorked(new BigDecimal(-1));
                    break;
                } else {
                    Minutes minutes = Minutes.minutesBetween(new DateTime(startCounterWork),
                            new DateTime(tickedJobs.get(i).getTicked()));
                    workedMinutes = workedMinutes.add(new BigDecimal(minutes.getMinutes()));
                    startCounterPause = tickedJobs.get(i).getTicked();
                }
            }

            tickedJobsDetail.setActualPause(pausedMinutes);
            tickedJobsDetail.setActualWorked(workedMinutes);
        }
    } else {
        tickedJobsDetail.setTickedJobs(tickedJobs);
        tickedJobsDetail.setActualWorked(new BigDecimal(0));
        tickedJobsDetail.setActualPause(new BigDecimal(0));
    }

    return tickedJobsDetail;
}

From source file:engine.Pi.java

/**
     * Compute the value, in radians, of the arctangent of 
     * the inverse of the supplied integer to the specified
     * number of digits after the decimal point.  The value
     * is computed using the power series expansion for the
     * arc tangent://from   w  ww  .  ja  v a 2 s  .c  om
     *
     * arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + 
     *     (x^9)/9 ...
     */
    public static BigDecimal arctan(int inverseX, int scale) {
        BigDecimal result, numer, term;
        BigDecimal invX = BigDecimal.valueOf(inverseX);
        BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX);

        numer = BigDecimal.ONE.divide(invX, scale, roundingMode);

        result = numer;
        int i = 1;
        do {
            numer = numer.divide(invX2, scale, roundingMode);
            int denom = 2 * i + 1;
            term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode);
            if ((i % 2) != 0) {
                result = result.subtract(term);
            } else {
                result = result.add(term);
            }
            i++;
        } while (term.compareTo(BigDecimal.ZERO) != 0);
        return result;
    }

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

/**
 * Add attributes to an OrderProduct and calculates the OrderProductPrice
 * accordingly//from w  ww  .j  av  a  2s  .c  o m
 * 
 * @param attributes
 * @param product
 * @param currency
 * @param locale
 * @return
 * @throws Exception
 */
public static OrderProduct addAttributesToProduct(List<OrderProductAttribute> attributes, OrderProduct product,
        String currency, Locale locale) throws Exception {

    Locale loc = locale;
    String lang = loc.getLanguage();

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

    BigDecimal sumPrice = null;

    // get attributes for this product
    Collection productAttributes = cservice.getProductAttributes(product.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);
        }
    }

    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) {
                    // try {
                    // sumPrice= new
                    // BigDecimal(attrPrice.doubleValue()).setScale(BigDecimal.ROUND_UNNECESSARY);
                    sumPrice = attrPrice;
                    // } catch (Exception e) {
                    // }

                } else {
                    BigDecimal currentPrice = sumPrice;
                    sumPrice = currentPrice.add(attrPrice);
                }
            }
            opa.setOrderProductId(product.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) {

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

        // added
        product.setProductPrice(productPrice);

        BigDecimal finalPrice = productPrice.multiply(new BigDecimal(product.getProductQuantity()));

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

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

    Set attributesSet = new HashSet(attributes);

    product.setOrderattributes(attributesSet);

    return product;
}

From source file:com.wms.utils.DataUtil.java

/**
 * add/*from  www.j a v  a  2s.  c  om*/
 *
 * @param obj1 BigDecimal
 * @param obj2 BigDecimal
 * @return BigDecimal
 */
public static BigDecimal add(BigDecimal obj1, BigDecimal obj2) {
    if (obj1 == null) {
        return obj2;
    } else if (obj2 == null) {
        return obj1;
    }

    return obj1.add(obj2);
}