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:com.salesmanager.core.util.CheckoutUtil.java

/**
 * Add attributes to an OrderProduct and calculates the OrderProductPrice
 * accordingly/*from w  w  w .  j av a  2  s .com*/
 * 
 * @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:edu.ku.brc.util.LatLonConverter.java

/**
 * @param str//from   www.j  a  v a  2s  . co m
 * @return
 */
public static BigDecimal convertDirectionalDDMMSSToDDDD(final String str) {
    String[] parts = StringUtils.split(str, " d'\"" + DEGREES_SYMBOL);

    String dir = null;
    if (parts.length < 4) {
        parts[2] = parts[2].replaceAll("[NSEW]", "");

        int beginIndex = str.indexOf(parts[2]) + parts[2].length();
        dir = str.substring(beginIndex, beginIndex + 1);
    } else {
        dir = parts[3].substring(0, 1);
    }

    double p0 = UIHelper.parseDouble(parts[0]);
    double p1 = UIHelper.parseDouble(parts[1]);
    double p2 = UIHelper.parseDouble(parts[2]);

    BigDecimal val = new BigDecimal(p0 + ((p1 + (p2 / 60.0)) / 60.0));

    if (isNegative(dir)) {
        val = val.multiply(minusOne);
    }

    return val;
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees and Decimal Minutes.
 * @param bd the DigDecimal to be converted.
 * @return a 2 piece string/*  w w w .ja v  a  2  s. co m*/
 */
public static String convertToDDMMMM(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {
    if (bd.doubleValue() == 0.0) {
        return "0.0";
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = remainder.multiply(sixty).abs();

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]");
        return decFormatter2.format(num) + " " + decFormatter2.format(minutes);

    }
    //else

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    //System.out.println("["+whole+"]["+String.format("%10.10f", new Object[] {minutes})+"]");

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append("\u00B0");
    }
    sb.append(' ');

    // round to four decimal places of precision
    //minutes = Math.round(minutes*10000) / 10000;

    sb.append(String.format("%" + 2 + "." + decimalLen + "f", minutes));
    if (addMinSecsSyms)
        sb.append("'");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //return whole + (degreesFMT == DEGREES_FORMAT.Symbol ? "\u00B0" : "") + " " + StringUtils.strip(String.format("%10.10f", new Object[] {minutes}), "0");
    return sb.toString();

}

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  . j  a v a2  s  . co 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:matrix.SquareMatrix.java

/**
 *
 * @param A a square matrix to calculate the determinant of, which is
 * returned// w ww  .j a v a2  s  .c om
 * @return
 */
public static BigDecimal determinant(SquareMatrix A) {
    try {
        LUP = new LUPDecomposition();
        LUP.decompose(A);
    } catch (NonInvertibleMatrixException ex) {
        LUP = null;
        return new BigDecimal(0.0);
    }
    BigDecimal det = new BigDecimal(1);
    double[][] u = LUP.U.getMatrix();
    /*
     System.out.println("\nA:\n" + A + "\nL:\n" + L + "\nU:\n" + U + "\nP:\n" + P + "\nperms:\n" + perms);
     try {
     System.out.println("Result of P.mult(A):\n" + P.mult(A));
     System.out.println("Result of L.mult(U):\n" + L.mult(U));
     } catch (DimensionMismatchException ex) {
     ex.printStackTrace();
     exit(-1);//this really shouldn't happen so i'm going to bail here
     }*/

    //still need to account for P matrix.  --done
    //L matrix is not used because it is a unit lower triangular matrix, 
    //and its main diagonal entries are all 1
    for (int i = 0; i < LUP.U.getRows(); ++i) {
        det = det.multiply(new BigDecimal(u[i][i]));
    }

    if (LUP.permutations % 2 != 0) {
        det = det.multiply(new BigDecimal(-1));
    }

    return det;
}

From source file:edu.ku.brc.specify.config.LatLonConverter.java

/**
 * Converts BigDecimal to Degrees, Minutes and Decimal Seconds.
 * @param bd the DigDecimal to be converted.
 * @return a 3 piece string/*  w w w  .  ja va  2 s .c  om*/
 */
public static String convertToDDMMSS(final BigDecimal bd, final DEGREES_FORMAT degreesFMT,
        final DIRECTION direction, final int decimalLen, final boolean alwaysIncludeDir) {

    if (bd.doubleValue() == 0.0) {
        return "0." + zeroes.substring(0, decimalLen);
    }

    if (useDB) {
        BigDecimal remainder = bd.remainder(one);

        BigDecimal num = bd.subtract(remainder);

        BigDecimal minutes = new BigDecimal(remainder.multiply(sixty).abs().intValue());
        BigDecimal secondsFraction = remainder.abs().multiply(sixty).subtract(minutes);
        BigDecimal seconds = secondsFraction.multiply(sixty);

        //System.out.println("["+decFormatter2.format(num)+"]["+minutes+"]["+seconds+"]");

        return decFormatter2.format(num) + " " + decFormatter2.format(minutes) + " "
                + decFormatter.format(seconds);

    }
    //else

    double num = Math.abs(bd.doubleValue());
    int whole = (int) Math.floor(num);
    double remainder = num - whole;

    double minutes = remainder * 60.0;
    int minutesWhole = (int) Math.floor(minutes);
    double secondsFraction = minutes - minutesWhole;
    double seconds = secondsFraction * 60.0;

    boolean addMinSecsSyms = degreesFMT != DEGREES_FORMAT.None;

    if (minutesWhole == 60) {
        whole += 1;
        minutesWhole = 0;
    }

    // round to 2 decimal places precision
    seconds = Math.round(seconds * 1000) / 1000.0;

    int secondsWhole = (int) Math.floor(seconds);
    if (secondsWhole == 60) {
        minutesWhole += 1;
        seconds = 0.0;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(whole);
    if (degreesFMT == DEGREES_FORMAT.Symbol) {
        sb.append(DEGREES_SYMBOL);
    }
    sb.append(' ');
    sb.append(minutesWhole);
    if (addMinSecsSyms)
        sb.append("'");
    sb.append(' ');

    sb.append(String.format("%2." + decimalLen + "f", seconds));
    if (addMinSecsSyms)
        sb.append("\"");

    if (degreesFMT == DEGREES_FORMAT.String || alwaysIncludeDir) {
        int inx = bd.doubleValue() < 0.0 ? 1 : 0;
        if (direction != DIRECTION.None) {
            sb.append(' ');
            sb.append(direction == DIRECTION.NorthSouth ? northSouth[inx] : eastWest[inx]);
        }
    }
    //System.err.println("["+sb.toString()+"]");
    //return whole + (DEGREES_FORMAT.None ? "\u00B0" : "") + " " + minutesWhole + " " + StringUtils.strip(String.format("%12.10f", new Object[] {seconds}), "0");
    return sb.toString();
}

From source file:de.olivergierke.whoops.options.OptionTransactionFeeProvider.java

public BigDecimal getTransactionFee(Instrument instrument) {

    Option option = (Option) instrument;
    Instrument underlying = option.getUnderlying();

    TransactionFeeProvider provider = feeProviders.getPluginFor(underlying);
    BigDecimal fee = provider.getTransactionFee(underlying);

    return fee.multiply(multiplier);
}

From source file:com.quinsoft.zeidon.domains.BigDecimalDomain.java

@Override
public Object multiplyAttribute(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        Object currentValue, Object operand) {
    BigDecimal num = (BigDecimal) convertExternalValue(task, attributeInstance, attributeDef, null, operand);
    BigDecimal value = (BigDecimal) currentValue;
    return value.multiply(num);
}

From source file:com.trenako.format.CurrencyFormatter.java

@Override
public Integer parse(String text, Locale locale) throws ParseException {
    Integer val = null;
    BigDecimal d = (BigDecimal) super.parse(text, locale);
    if (d != null) {
        val = d.multiply(RATIO).intValue();
    }//from   w  w  w.  j a va  2 s  .  c om
    return val;
}

From source file:com.trenako.format.GaugeFormatter.java

@Override
public Integer parse(String text, Locale locale) throws ParseException {
    Integer val = null;
    BigDecimal d = (BigDecimal) super.parse(text, locale);
    if (d != null) {
        val = d.multiply(Scale.GAUGE_FACTOR).intValue();
    }/*from   w  w w  .ja va2s  . co  m*/
    return val;
}