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.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax/*ww w  .  j  a  v a2  s.  c  om*/
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:org.chiba.xml.xforms.ui.Range.java

/**
 * Initializes this range.//from w  ww  .  j  a va  2  s . c o  m
 *
 * @throws XFormsException if the datatype of the bound is not supported.
 */
protected final void initializeRange() throws XFormsException {
    if (!isBound()) {
        return;
    }

    // get model item datatype
    Validator validator = this.model.getValidator();
    String datatype = getDatatype();

    if (validator.isRestricted("decimal", datatype) || validator.isRestricted("float", datatype)
            || validator.isRestricted("double", datatype)) {
        // get bound value
        String value = getInstanceValue();
        BigDecimal valueDecimal;
        if (value != null && value.length() > 0) {
            valueDecimal = new BigDecimal(value);
        } else {
            // set '0.0' as default value
            valueDecimal = new BigDecimal(0d);
        }

        // get step size
        BigDecimal stepDecimal;
        String stepAttribute = getXFormsAttribute(STEP_ATTRIBUTE);
        if (stepAttribute != null) {
            stepDecimal = new BigDecimal(stepAttribute);
        } else {
            // set '1.0' as default step
            stepDecimal = new BigDecimal(1d);
            this.element.setAttributeNS(null, STEP_ATTRIBUTE, stepDecimal.toString());
        }

        // get range start
        BigDecimal startDecimal;
        String startAttribute = getXFormsAttribute(START_ATTRIBUTE);
        if (startAttribute != null) {
            startDecimal = new BigDecimal(startAttribute);
        } else {
            // set 'value - (2 * step)' as default start
            startDecimal = valueDecimal.subtract(stepDecimal.multiply(new BigDecimal(2d)));
            this.element.setAttributeNS(null, START_ATTRIBUTE, startDecimal.toString());
        }

        // get range end
        BigDecimal endDecimal;
        String endAttribute = getXFormsAttribute(END_ATTRIBUTE);
        if (endAttribute != null) {
            endDecimal = new BigDecimal(endAttribute);
        } else {
            // set 'value + (2 * step)' as default end
            endDecimal = valueDecimal.add(stepDecimal.multiply(new BigDecimal(2d)));
            this.element.setAttributeNS(null, END_ATTRIBUTE, endDecimal.toString());
        }

        if (valueDecimal.compareTo(startDecimal) < 0 || valueDecimal.compareTo(endDecimal) > 0) {
            this.model.getContainer().dispatch(this.target, XFormsEventNames.OUT_OF_RANGE, null);
        }

        return;
    }

    throw new XFormsBindingException("datatype not supported by range control", this.target, datatype);
}

From source file:fsm.series.Series_CF.java

public double getF4Value(double y, int m, int n) {
    double Pi = Math.PI;

    double um = getMu_m(m);
    double un = getMu_m(n);
    double alphaM = (sin(um) + sinh(um)) / (cos(um) + cosh(um));

    double alphaN = (sin(un) + sinh(un)) / (cos(un) + cosh(un));
    double km = um / a;
    double kn = un / a;

    BigDecimal Ymd2;
    BigDecimal Ynd2;/*ww  w .  j  av  a2 s  .  c om*/

    BigDecimal cosh = new BigDecimal(alphaM * km * km * cosh(km * y));

    BigDecimal sinh = new BigDecimal(-km * km * sinh(km * y));
    BigDecimal sin = new BigDecimal(-km * km * sin(km * y));
    BigDecimal cos = new BigDecimal(alphaM * km * km * cos(km * y));

    Ymd2 = (cos.add(sin).add(sinh).add(cosh));

    BigDecimal coshN = new BigDecimal(alphaN * kn * kn * cosh(kn * y));

    BigDecimal sinhN = new BigDecimal(-kn * kn * sinh(kn * y));
    BigDecimal sinN = new BigDecimal(-kn * kn * sin(kn * y));
    BigDecimal cosN = new BigDecimal(alphaN * kn * kn * cos(kn * y));

    Ynd2 = cosN.add(sinN).add(sinhN).add(coshN);

    BigDecimal ans = Ymd2.multiply(Ynd2);

    return ans.doubleValue();
}

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private BigDecimal calculateDemandWithRecursiveAmount(final UsageSlab usageSlab,
        final MeteredRatesDetail meteredRatesDetail, final BigDecimal numberOfUnitsPerMonth) {
    BigDecimal totalAmount = BigDecimal.ZERO;
    BigDecimal amtValue;
    BigDecimal amount1;/*www  . j a  v a2 s  .  c  om*/
    BigDecimal amount2;
    if (meteredRatesDetail.getFlatAmount() != null && meteredRatesDetail.getFlatAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amtValue = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor())
                        .setScale(0, BigDecimal.ROUND_HALF_UP));
        totalAmount = BigDecimal.valueOf(meteredRatesDetail.getFlatAmount())
                .add(amtValue.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())));
    } else if (meteredRatesDetail.getRateAmount() != null && meteredRatesDetail.getRateAmount() != 0
            && numberOfUnitsPerMonth.compareTo(BigDecimal.valueOf(usageSlab.getFromVolume())) > -1) {
        amount1 = BigDecimal.valueOf(usageSlab.getFromVolume()).subtract(BigDecimal.ONE)
                .multiply(BigDecimal.valueOf(meteredRatesDetail.getRateAmount()));
        amount2 = numberOfUnitsPerMonth.subtract(BigDecimal.valueOf(usageSlab.getFromVolume()))
                .add(BigDecimal.ONE).divide(BigDecimal.valueOf(meteredRatesDetail.getRecursiveFactor()), 0,
                        BigDecimal.ROUND_HALF_UP);
        amtValue = amount2.multiply(BigDecimal.valueOf(meteredRatesDetail.getRecursiveAmount())).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        totalAmount = amount1.add(amtValue);
    }
    return totalAmount;
}

From source file:com.konakart.bl.modules.ordertotal.productdiscount.ProductDiscount.java

/**
 * Create and return an OrderTotal object for the discount amount. *
 * <p>//from   ww  w.  jav  a  2 s  .  c  om
 * Custom field usage:
 * <p>
 * <ul>
 * <li>custom1 = Minimum Order Value</li>
 * <li>custom2 = Minimum quantity of a single product</li>
 * <li>custom3 = Discount Applied</li>
 * <li>custom4 = Percentage discount if set to true</li>
 * <li>custom5 = Discount applied to pre-tax value if set to true</li>
 * </ul>
 * If the promotion applies to multiple products, we create an array of order total objects and
 * attach the array to the order total that we return (ot.setOrderTotals(otArray)). The reason
 * for doing this is to get a line item of the order for each discounted product. We still need
 * to populate the order total that we return with the total discount amount because this will
 * be used to compare this promotion with other promotions in order to decide which one to use.
 * 
 * @param order
 * @param dispPriceWithTax
 * @param locale
 * @return Returns an OrderTotal object for this module
 * @throws Exception
 */
public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale) throws Exception {
    OrderTotal ot;
    StaticData sd = staticDataHM.get(getStoreId());

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale);
    if (rb == null) {
        throw new KKException("A resource file cannot be found for the country " + locale.getCountry());
    }

    // Get the promotions
    Promotion[] promArray = getPromMgr().getPromotions(code, order);

    // List to contain an order total for each promotion
    List<OrderTotal> orderTotalList = new ArrayList<OrderTotal>();

    if (promArray != null) {

        for (int i = 0; i < promArray.length; i++) {
            Promotion promotion = promArray[i];

            /*
             * Get the configuration parameters from the promotion
             */

            // Minimum value for order
            BigDecimal minTotalOrderVal = getCustomBigDecimal(promotion.getCustom1(), 1);

            // Need to order at least this quantity of a single product for promotion to apply
            int minProdQuantity = getCustomInt(promotion.getCustom2(), 2);

            // Actual discount. Could be a percentage or an amount.
            BigDecimal discountApplied = getCustomBigDecimal(promotion.getCustom3(), 3);

            // If set to true it is a percentage. Otherwise it is an amount.
            boolean percentageDiscount = getCustomBoolean(promotion.getCustom4(), 4);

            // If set to true, discount is applied to pre-tax value. Only relevant for
            // percentage discount.
            boolean applyBeforeTax = getCustomBoolean(promotion.getCustom5(), 5);

            // Don't bother going any further if there is no discount
            if (discountApplied == null || discountApplied.equals(new BigDecimal(0))) {
                continue;
            }

            // Get the order value
            BigDecimal orderValue = null;
            if (applyBeforeTax) {
                orderValue = order.getSubTotalExTax();
                log.debug("Order value before tax: " + orderValue);
            } else {
                orderValue = order.getSubTotalIncTax();
                log.debug("Order value after tax: " + orderValue);
            }

            // If promotion doesn't cover any of the products in the order then go on to the
            // next promotion
            if (promotion.getApplicableProducts() == null || promotion.getApplicableProducts().length == 0) {
                continue;
            }

            ot = new OrderTotal();
            ot.setSortOrder(sd.getSortOrder());
            ot.setClassName(code);
            ot.setPromotions(new Promotion[] { promotion });

            // Does promotion only apply to a min order value ?
            if (minTotalOrderVal != null) {
                if (orderValue.compareTo(minTotalOrderVal) < 0) {
                    // If we haven't reached the minimum amount then continue to the next
                    // promotion
                    continue;
                }
            }

            // Continue if promotion has no applicable products (should never happen)
            if (promotion.getApplicableProducts() == null) {
                continue;
            }

            /*
             * Create a new Order Total module for each discounted product and store in this
             * list
             */
            ArrayList<OrderTotal> otList = new ArrayList<OrderTotal>();

            // Loop through promotion products to determine whether to apply a discount
            boolean firstLoop = true;
            for (int j = 0; j < promotion.getApplicableProducts().length; j++) {
                OrderProductIf op = promotion.getApplicableProducts()[j];
                if (op != null && op.getQuantity() >= minProdQuantity) {
                    // Get the current total price of the product(s)
                    BigDecimal currentPrice = null;
                    if (applyBeforeTax) {
                        currentPrice = op.getFinalPriceExTax();
                    } else {
                        currentPrice = op.getFinalPriceIncTax();
                    }

                    // Apply the discount
                    BigDecimal discount = null;
                    if (percentageDiscount) {
                        // Apply a percentage discount
                        discount = (currentPrice.multiply(discountApplied)).divide(new BigDecimal(100));
                    } else {
                        // Apply an amount based discount
                        discount = discountApplied.multiply(new BigDecimal(op.getQuantity()));
                    }

                    // Determine whether it is the first discounted product or not
                    String formattedDiscount = getCurrMgr().formatPrice(discount, order.getCurrencyCode());
                    if (firstLoop) {
                        // Set the order total attributes
                        ot.setValue(discount);
                        if (percentageDiscount) {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", discountApplied, "%", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10% Philips TV"
                                ot.setTitle("-" + discountApplied + "% " + op.getName());
                            }

                        } else {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", formattedDiscount, "", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10EUR Philips TV"
                                ot.setTitle("-" + formattedDiscount + " " + op.getName());
                            }
                        }
                    } else {
                        // Set the order total attributes
                        ot.setValue(ot.getValue().add(discount));
                        ot.setText("-" + getCurrMgr().formatPrice(ot.getValue(), order.getCurrencyCode()));
                        ot.setTitle(ot.getTitle() + "," + op.getName());
                    }
                    firstLoop = false;

                    /*
                     * Create a new Order Total module for each product
                     */
                    OrderTotal singleOt = new OrderTotal();
                    singleOt.setSortOrder(sd.getSortOrder());
                    singleOt.setClassName(code);
                    singleOt.setValue(discount);
                    singleOt.setText("-" + formattedDiscount);
                    if (percentageDiscount) {
                        singleOt.setTitle("-" + discountApplied + "% " + op.getName() + ":");
                    } else {
                        singleOt.setTitle("-" + formattedDiscount + " " + op.getName() + ":");
                    }
                    otList.add(singleOt);
                }
            }

            /*
             * If we have more than one discounted product we create an array of order totals
             * (one for each product) and add the array to the order total to be returned.
             */
            if (otList.size() > 1) {
                OrderTotal[] otArray = new OrderTotal[otList.size()];
                int k = 0;
                for (Iterator<OrderTotal> iterator = otList.iterator(); iterator.hasNext();) {
                    OrderTotal lot = iterator.next();
                    otArray[k++] = lot;
                }
                ot.setOrderTotals(otArray);
            }

            if (ot.getValue() != null) {
                int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue();
                ot.setValue(ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP));
                log.debug("Order total is :" + ot.toString());
                orderTotalList.add(ot);
            }
        }
    } else {
        // Return null if there are no promotions
        return null;
    }

    // Call a helper method to decide which OrderTotal we should return
    OrderTotal retOT = getDiscountOrderTotalFromList(order, orderTotalList);
    log.debug("Selected order total is: " + retOT);

    return retOT;

}

From source file:fsm.series.Series_CC.java

public strictfp double getF1Value(double y, int m, int n) {

    double um = getMu_m(m);
    double un = getMu_m(n);

    double alphaM = (sin(um) - sinh(um)) / (cos(um) - cosh(um));

    double alphaN = (sin(un) - sinh(un)) / (cos(un) - cosh(un));

    double km = um / a;
    double kn = un / a;

    BigDecimal Ym;
    BigDecimal Yn;//w  w w.j  a  v  a  2  s  .co m

    BigDecimal cosh = new BigDecimal(-alphaM * -cosh(km * y));
    BigDecimal sinh = new BigDecimal(-sinh(km * y));
    BigDecimal sin = new BigDecimal(sin(km * y));
    BigDecimal cos = new BigDecimal(-alphaM * cos(km * y));

    Ym = (cos.add(sin).add(sinh).add(cosh));

    BigDecimal coshN = new BigDecimal(-alphaN * -cosh(kn * y));
    BigDecimal sinhN = new BigDecimal(-sinh(kn * y));
    BigDecimal sinN = new BigDecimal(sin(kn * y));
    BigDecimal cosN = new BigDecimal(-alphaN * cos(kn * y));

    Yn = cosN.add(sinN).add(sinhN).add(coshN);

    BigDecimal ans = Ym.multiply(Yn);

    return ans.doubleValue();

}

From source file:org.libreplan.web.orders.OrderModel.java

private BigDecimal getHoursAdvancePercentage(Order order) {
    BigDecimal result;
    if (order != null) {
        result = orderElementDAO.getHoursAdvancePercentage(order);
    } else {/* w ww .j a  va2  s .  c  om*/
        result = new BigDecimal(0);
    }

    return result.multiply(new BigDecimal(100));
}

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

/**
 * @param _oldValue old Value//from w  w  w  .j  a v  a2s. co m
 * @param _oldRate old Rate
 * @param _newRate new Rate
 * @return new Value
 */
protected BigDecimal getNewValue(final BigDecimal _oldValue, final BigDecimal _oldRate,
        final BigDecimal _newRate) {
    BigDecimal ret = BigDecimal.ZERO;
    if (_oldValue.compareTo(BigDecimal.ZERO) != 0) {
        ret = _oldValue.multiply(_oldRate).divide(_newRate, BigDecimal.ROUND_HALF_UP).setScale(2,
                BigDecimal.ROUND_HALF_UP);
    }
    return ret;
}

From source file:org.apache.fineract.portfolio.servicecharge.service.ServiceChargeJournalDetailsReadPlatformServiceImpl.java

private Map<GLExpenseTagsForServiceCharge, BigDecimal> apportionMobilization(
        Map<GLExpenseTagsForServiceCharge, BigDecimal> dataMap) {
    Map<GLExpenseTagsForServiceCharge, BigDecimal> resultMap = new HashMap<>();
    BigDecimal mobilizationAmount = new BigDecimal(
            dataMap.get(GLExpenseTagsForServiceCharge.MOBILIZATION).toPlainString());
    BigDecimal servicingAmount = new BigDecimal(
            dataMap.get(GLExpenseTagsForServiceCharge.SERVICING).toPlainString());
    BigDecimal investmentAmount = new BigDecimal(
            dataMap.get(GLExpenseTagsForServiceCharge.INVESTMENT).toPlainString());
    BigDecimal dlAmount = BigDecimal.ONE;
    BigDecimal outstandingLoanAmount = BigDecimal.ONE;

    BigDecimal multiplicand = BigDecimal.ONE.multiply(dlAmount);
    multiplicand = ServiceChargeOperationUtils.divideNonZeroValues(multiplicand, outstandingLoanAmount);

    servicingAmount = mobilizationAmount.multiply(multiplicand);
    investmentAmount = mobilizationAmount.subtract(servicingAmount);

    resultMap.put(GLExpenseTagsForServiceCharge.SERVICING, servicingAmount);
    resultMap.put(GLExpenseTagsForServiceCharge.INVESTMENT, investmentAmount);

    return resultMap;
}

From source file:org.kuali.kfs.module.endow.document.validation.impl.HoldingHistoryValueAdjustmentDocumentRules.java

/**
 * Calculates unit value when security id's valuation method is M and market value is entered.
 *//*from  w  w  w .  ja  v  a  2s  .  co  m*/
protected BigDecimal calculateUnitValueWhenMarketValueEntered(HoldingHistoryValueAdjustmentDocument document) {
    BigDecimal unitValue = BigDecimal.ZERO;
    BigDecimal totalUnits = BigDecimal.ZERO;

    BigDecimal marketValue = document.getSecurityMarketValue();

    Collection<HoldingHistory> holdingHistoryRecords = SpringContext.getBean(HoldingHistoryService.class)
            .getHoldingHistoryBySecuritIdAndMonthEndId(document.getSecurityId(),
                    document.getHoldingMonthEndDate());
    for (HoldingHistory holdingHistory : holdingHistoryRecords) {
        totalUnits = totalUnits.add(holdingHistory.getUnits()); // sum up the units and store it
    }

    ClassCode classCode = document.getSecurity().getClassCode();

    if (ObjectUtils.isNotNull(classCode) && ObjectUtils.isNotNull(totalUnits)
            && totalUnits.compareTo(BigDecimal.ZERO) != 0) {
        if (EndowConstants.ClassCodeTypes.BOND.equalsIgnoreCase(classCode.getClassCodeType())) {
            unitValue = KEMCalculationRoundingHelper.divide((marketValue.multiply(new BigDecimal(100))),
                    totalUnits, EndowConstants.Scale.SECURITY_UNIT_VALUE);
        } else {
            unitValue = KEMCalculationRoundingHelper.divide(marketValue, totalUnits,
                    EndowConstants.Scale.SECURITY_UNIT_VALUE);
        }
    }

    return unitValue;
}