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.trenako.format.RatioFormatter.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.RATIO_FACTOR).intValue();
    }//from w  w  w  .  ja v  a2s  .  com
    return val;
}

From source file:be.error.rpi.adc.ObjectStatusReader.java

@Override
public Pair<AdcChannel, ObjectStatusType> apply(final AdcChannel adcChannel) {
    try {/*from w  w w  . j a v a  2s.  c  o m*/
        byte readResult[] = adcChannel.getAdc().read(adcChannel);
        BitSet conversion = valueOf(new byte[] { readResult[1], readResult[0] });

        ObjectStatusType objectStatusType = READ_ERROR;

        if (!conversion.get(15)) {
            long[] l = conversion.toLongArray();
            if (l != null && l.length == 1) {
                BigDecimal value = new BigDecimal(l[0]);
                BigDecimal voltage = value.multiply(step).setScale(2, HALF_UP);
                objectStatusType = objectStatusTypeMapper.map(voltage);
            }
        }
        return of(adcChannel, objectStatusType);
    } catch (IOException ioException) {
        logger.error("Could not read from channel", ioException);
        throw new RuntimeException(ioException);
    }
}

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

/**
 * OrderProductAttribute is configured from javascript This code needs to
 * invoke catalog objects require getProductOptionValueId
 * /*from   w  ww . ja  va  2  s .c  o  m*/
 * @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:jp.co.acroquest.endosnipe.report.converter.util.calc.BigDecimalCalculator.java

public Object mul(Object obj1, Object obj2) {
    BigDecimal decimalData1 = (BigDecimal) obj1;
    BigDecimal decimalData2 = (BigDecimal) obj2;

    return (Object) (decimalData1.multiply(decimalData2));
}

From source file:org.cirdles.calamari.algorithms.TukeyBiweight.java

public static ValueModel calculateTukeyBiweightMean(String name, double tuningConstant, double[] values) {
    // guarantee termination
    BigDecimal epsilon = BigDecimal.ONE.movePointLeft(10);
    int iterationMax = 100;
    int iterationCounter = 0;

    int n = values.length;
    // initial mean is median
    BigDecimal mean = new BigDecimal(calculateMedian(values));

    // initial sigma is median absolute deviation from mean = median (MAD)
    double deviations[] = new double[n];
    for (int i = 0; i < values.length; i++) {
        deviations[i] = StrictMath.abs(values[i] - mean.doubleValue());
    }//from w  w w  .  ja va2  s.  com
    BigDecimal sigma = new BigDecimal(calculateMedian(deviations)).max(BigDecimal.valueOf(SQUID_TINY_VALUE));

    BigDecimal previousMean;
    BigDecimal previousSigma;

    do {
        iterationCounter++;
        previousMean = mean;
        previousSigma = sigma;

        // init to zeroes
        BigDecimal[] deltas = new BigDecimal[n];
        BigDecimal[] u = new BigDecimal[n];
        BigDecimal sa = BigDecimal.ZERO;
        BigDecimal sb = BigDecimal.ZERO;
        BigDecimal sc = BigDecimal.ZERO;

        BigDecimal tee = new BigDecimal(tuningConstant).multiply(sigma);

        for (int i = 0; i < n; i++) {
            deltas[i] = new BigDecimal(values[i]).subtract(mean);
            if (tee.compareTo(deltas[i].abs()) > 0) {
                deltas[i] = new BigDecimal(values[i]).subtract(mean);
                u[i] = deltas[i].divide(tee, MathContext.DECIMAL128);
                BigDecimal uSquared = u[i].multiply(u[i]);
                sa = sa.add(deltas[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)).pow(2));
                sb = sb.add(BigDecimal.ONE.subtract(uSquared)
                        .multiply(BigDecimal.ONE.subtract(new BigDecimal(5.0).multiply(uSquared))));
                sc = sc.add(u[i].multiply(BigDecimal.ONE.subtract(uSquared).pow(2)));
            }
        }

        sigma = bigDecimalSqrtBabylonian(sa.multiply(new BigDecimal(n))).divide(sb.abs(),
                MathContext.DECIMAL128);
        sigma = sigma.max(BigDecimal.valueOf(SQUID_TINY_VALUE));
        mean = previousMean.add(tee.multiply(sc).divide(sb, MathContext.DECIMAL128));

    } // both tests against epsilon must pass OR iterations top out
      // april 2016 Simon B discovered we need 101 iterations possible, hence the "<=" below
    while (((sigma.subtract(previousSigma).abs().divide(sigma, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            || mean.subtract(previousMean).abs().divide(mean, MathContext.DECIMAL128).compareTo(epsilon) > 0)//
            && (iterationCounter <= iterationMax));

    return new ValueModel(name, mean, "ABS", sigma);
}

From source file:kr.ac.kaist.se.simulator.NormalDistributor.java

public int getNextVal() {
    String _val = Double.toString(this.distGenerator.sample());
    BigDecimal dec = new BigDecimal(_val);
    BigDecimal std = new BigDecimal(Integer.toString(this.stDev));
    dec = dec.add(new BigDecimal(Integer.toString(mean)));
    std = std.multiply(new BigDecimal(_val));
    int retVal = dec.add(std).toBigInteger().intValue();
    return retVal;
}

From source file:org.openbravo.costing.PriceDifferenceProcess.java

private static boolean calculateTransactionPriceDifferenceLogic(MaterialTransaction materialTransaction)
        throws OBException {
    boolean costAdjCreated = false;

    // With Standard Algorithm, no cost adjustment is needed
    if (StringUtils.equals(materialTransaction.getCostingAlgorithm().getJavaClassName(),
            "org.openbravo.costing.StandardAlgorithm")) {
        return false;
    }//from   ww  w.ja  v a  2s. c  om

    if (materialTransaction.isCostPermanent()) {
        // Permanently adjusted transaction costs are not checked for price differences.
        return false;
    }
    Currency trxCurrency = materialTransaction.getCurrency();
    Organization trxOrg = materialTransaction.getOrganization();
    Date trxDate = materialTransaction.getMovementDate();
    int costCurPrecission = trxCurrency.getCostingPrecision().intValue();
    ShipmentInOutLine receiptLine = materialTransaction.getGoodsShipmentLine();
    if (receiptLine == null
            || !isValidPriceAdjTrx(receiptLine.getMaterialMgmtMaterialTransactionList().get(0))) {
        // We can only adjust cost of receipt lines.
        return false;
    }

    BigDecimal receiptQty = receiptLine.getMovementQuantity();
    boolean isNegativeReceipt = receiptQty.signum() == -1;
    if (isNegativeReceipt) {
        // If the receipt is negative convert the quantity to positive.
        receiptQty = receiptQty.negate();
    }

    Date costAdjDateAcct = null;
    BigDecimal invoiceAmt = BigDecimal.ZERO;

    // Calculate current transaction unit cost including existing adjustments.
    BigDecimal currentTrxUnitCost = CostAdjustmentUtils.getTrxCost(materialTransaction, true, trxCurrency);

    // Calculate expected transaction unit cost based on current invoice amounts and purchase price.
    BigDecimal expectedCost = BigDecimal.ZERO;
    BigDecimal invoiceQty = BigDecimal.ZERO;
    for (ReceiptInvoiceMatch matchInv : receiptLine.getProcurementReceiptInvoiceMatchList()) {
        Invoice invoice = matchInv.getInvoiceLine().getInvoice();
        if (invoice.getDocumentStatus().equals("VO")) {
            // Skip voided invoices.
            continue;
        }
        if (!invoice.isProcessed()) {
            // Skip not processed invoices.
            continue;
        }
        if (isNegativeReceipt) {
            // If the receipt is negative negate the invoiced quantities.
            invoiceQty = invoiceQty.add(matchInv.getQuantity().negate());
        } else {
            invoiceQty = invoiceQty.add(matchInv.getQuantity());
        }
        invoiceAmt = matchInv.getQuantity().multiply(matchInv.getInvoiceLine().getUnitPrice());

        invoiceAmt = FinancialUtils.getConvertedAmount(invoiceAmt, invoice.getCurrency(), trxCurrency, trxDate,
                trxOrg, FinancialUtils.PRECISION_STANDARD, invoice.getCurrencyConversionRateDocList());
        expectedCost = expectedCost.add(invoiceAmt);

        Date invoiceDate = invoice.getInvoiceDate();
        if (costAdjDateAcct == null || costAdjDateAcct.before(invoiceDate)) {
            costAdjDateAcct = invoiceDate;
        }
    }

    BigDecimal notInvoicedQty = receiptQty.subtract(invoiceQty);
    if (notInvoicedQty.signum() > 0) {
        // Not all the receipt line is invoiced, add pending invoice quantity valued with current
        // order price if exists or original unit cost.
        BigDecimal basePrice = BigDecimal.ZERO;
        Currency baseCurrency = trxCurrency;
        if (receiptLine.getSalesOrderLine() != null) {
            basePrice = receiptLine.getSalesOrderLine().getUnitPrice();
            baseCurrency = receiptLine.getSalesOrderLine().getSalesOrder().getCurrency();
        } else {
            basePrice = materialTransaction.getTransactionCost().divide(receiptQty, costCurPrecission,
                    RoundingMode.HALF_UP);
        }
        BigDecimal baseAmt = notInvoicedQty.multiply(basePrice).setScale(costCurPrecission,
                RoundingMode.HALF_UP);
        if (!baseCurrency.getId().equals(trxCurrency.getId())) {
            baseAmt = FinancialUtils.getConvertedAmount(baseAmt, baseCurrency, trxCurrency, trxDate, trxOrg,
                    FinancialUtils.PRECISION_STANDARD);
        }
        expectedCost = expectedCost.add(baseAmt);
    }
    // if the sum of trx costs with flag "isInvoiceCorrection" is distinct that the amount cost
    // generated by Match Invoice then New Cost Adjustment line is created by the difference
    if (expectedCost.compareTo(currentTrxUnitCost) != 0) {
        if (costAdjDateAcct == null) {
            costAdjDateAcct = trxDate;
        }
        createCostAdjustmenHeader(trxOrg);
        CostAdjustmentLine costAdjLine = CostAdjustmentUtils.insertCostAdjustmentLine(materialTransaction,
                costAdjHeader, expectedCost.subtract(currentTrxUnitCost), Boolean.TRUE, costAdjDateAcct);
        costAdjLine.setNeedsPosting(Boolean.TRUE);
        OBDal.getInstance().save(costAdjLine);
        costAdjCreated = true;
    }

    return costAdjCreated;
}

From source file:org.apache.hadoop.hbase.client.coprocessor.BigDecimalColumnInterpreter.java

@Override
public BigDecimal multiply(BigDecimal val1, BigDecimal val2) {
    return (((val1 == null) || (val2 == null)) ? null
            : val1.multiply(val2).setScale(2, RoundingMode.HALF_EVEN));
}

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   w w w.j  a  va2s .  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:com.coinblesk.client.utils.UIUtils.java

public static Coin getValue(Context context, long amount) {
    BigDecimal bdAmount = new BigDecimal(amount);
    BigDecimal multiplicand = new BigDecimal(Coin.COIN.getValue());

    if (SharedPrefUtils.isBitcoinScaleBTC(context)) {
        multiplicand = new BigDecimal(Coin.COIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) {
        multiplicand = new BigDecimal((Coin.MILLICOIN.getValue()));
    } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) {
        multiplicand = new BigDecimal((Coin.MICROCOIN.getValue()));
    }/*from  w  w  w. j ava2s  .c  o m*/
    return Coin.valueOf((bdAmount.multiply(multiplicand).longValue()));
}