Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:act.reports.dao.AllInvoicesDAO.java

public String roundUp(float d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(Float.toString(d));
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.toString();
}

From source file:org.egov.ptis.service.utils.PropertyTaxCommonUtils.java

public String formatAmount(BigDecimal tax) {
    tax = tax.setScale(0, RoundingMode.CEILING);
    return NumberUtil.formatNumber(tax);
}

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

/**
 * Gets the JS 4 fit exchange rate.// w ww .ja  v  a  2s. c o  m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fit ex rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FitExRate(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0
                                && BigDecimal.ZERO.compareTo(currAmount) < 0) {
                            final BigDecimal rate;
                            if (rateInfo.isInvert()) {
                                rate = targetRate.setScale(8, RoundingMode.HALF_UP).divide(currAmount,
                                        RoundingMode.HALF_UP);
                            } else {
                                rate = currAmount.setScale(8, RoundingMode.HALF_UP).divide(targetRate,
                                        RoundingMode.HALF_UP);
                            }

                            final String rateStr = NumberFormatter.get().getFormatter(null, 8).format(rate);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr))
                                    .append(getSetFieldValue(i, "rate_" + postfix, rateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);
                            ParameterUtil.setParameterValue(_parameterClone, "rate_" + postfix, i, rateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:com.salesmanager.core.module.impl.integration.shipping.FedexRequestQuotesImpl.java

public Collection<ShippingOption> getQuote(String carrier, String deliveryType, String module,
        Collection<PackageDetail> packages, BigDecimal orderTotal, ConfigurationResponse vo,
        MerchantStore store, Customer customer, Locale locale) throws Exception {
    // Build a RateRequest request object
    boolean getAllRatesFlag = true; // set to true to get the rates for
    // different service types
    RateRequest request = new RateRequest();
    request.setClientDetail(createClientDetail(module, vo));
    request.setWebAuthenticationDetail(createWebAuthenticationDetail(module, vo));

    Collection returnColl = null;
    int icountry = store.getCountry();
    String country = CountryUtil.getCountryIsoCodeById(icountry);

    IntegrationProperties props = (IntegrationProperties) vo.getConfiguration(module + "-properties");

    ShippingService sservice = (ShippingService) ServiceFactory.getService(ServiceFactory.ShippingService);
    CoreModuleService cms = sservice.getRealTimeQuoteShippingService(country, module);

    /** Details on whit RT quote information to display **/
    MerchantConfiguration rtdetails = vo
            .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
    int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
    if (rtdetails != null) {

        if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
            // or
            // not
            // quotes
            try {
                displayQuoteDeliveryTime = Integer.parseInt(rtdetails.getConfigurationValue1());

            } catch (Exception e) {
                log.error("Display quote is not an integer value [" + rtdetails.getConfigurationValue1() + "]");
            }/*from ww  w .  jav a 2 s .  c  om*/
        }
    }
    /**/

    if (cms == null) {
        // throw new
        // Exception("Central integration services not configured for " +
        // PaymentConstants.PAYMENT_PSIGATENAME + " and country id " +
        // origincountryid);
        log.error("CoreModuleService not configured for " + carrier + " and country id " + icountry);
        return null;
    }

    String host = cms.getCoreModuleServiceProdDomain();
    String protocol = cms.getCoreModuleServiceProdProtocol();
    String port = cms.getCoreModuleServiceProdPort();
    String url = cms.getCoreModuleServiceProdEnv();
    if (props.getProperties1().equals(String.valueOf(ShippingConstants.TEST_ENVIRONMENT))) {
        host = cms.getCoreModuleServiceDevDomain();
        protocol = cms.getCoreModuleServiceDevProtocol();
        port = cms.getCoreModuleServiceDevPort();
        url = cms.getCoreModuleServiceDevEnv();
    }

    //
    TransactionDetail transactionDetail = new TransactionDetail();
    transactionDetail.setCustomerTransactionId("Shopizer salesmanager"); // The
    // client
    // will
    // get
    // the
    // same
    // value
    // back
    // in
    // the
    // response
    request.setTransactionDetail(transactionDetail);

    //
    VersionId versionId = new VersionId("crs", 5, 0, 0);
    request.setVersion(versionId);

    //
    RequestedShipment requestedShipment = new RequestedShipment();

    requestedShipment.setShipTimestamp(Calendar.getInstance());
    requestedShipment.setDropoffType(DropoffType.REGULAR_PICKUP);

    MerchantConfiguration packageServices = vo
            .getMerchantConfiguration(module + "-" + ShippingConstants.MODULE_SHIPPING_RT_PKG_DOM_INT);
    String packageOption = packageServices.getConfigurationValue();

    PackagingType pType = getPackagingType(packageOption);

    if (deliveryType != null) {
        // requestedShipment.setServiceType(sType);
        ServiceType sType = getServiceType(deliveryType);
    }

    // if (! getAllRatesFlag) {
    // requestedShipment.setServiceType(ServiceType.INTERNATIONAL_PRIORITY);
    // requestedShipment.setServiceType(sType);
    requestedShipment.setPackagingType(pType);
    // }

    //

    Map countriesMap = (Map) RefCache
            .getAllcountriesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
    Country c = (Country) countriesMap.get(store.getCountry());

    Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
    // Zone z = CountryUtil.getZoneCodeByName(store.getZone(),
    // LanguageUtil.getLanguageNumberCode(locale.getCountry()));

    Zone zone = (Zone) zonesMap.get(Integer.parseInt(store.getZone()));
    String zoneName = null;
    if (zone == null) {
        zoneName = "N/A";
    } else {
        zoneName = zone.getZoneCode();
    }

    /*
     * String originZone = zoneName; if(originZone.endsWith("QC")) {
     * originZone = "PQ"; }
     */

    // origin
    Party shipper = new Party();
    Address shipperAddress = new Address(); // Origin information
    shipperAddress.setStreetLines(new String[] { store.getStoreaddress() });
    shipperAddress.setCity(store.getStorecity());
    shipperAddress.setStateOrProvinceCode(zoneName);
    shipperAddress
            .setPostalCode(com.salesmanager.core.util.ShippingUtil.trimPostalCode(store.getStorepostalcode()));
    shipperAddress.setCountryCode(c.getCountryIsoCode2());
    shipper.setAddress(shipperAddress);
    requestedShipment.setShipper(shipper);

    Zone customerZone = (Zone) zonesMap.get(customer.getCustomerZoneId());
    Country customerCountry = (Country) countriesMap.get(customer.getCustomerCountryId());
    String customerZoneName = null;
    if (zone == null) {
        customerZoneName = "N/A";
    } else {
        customerZoneName = customerZone.getZoneCode();
    }

    /*
     * String destZone = customerZoneName; if(destZone.endsWith("QC")) {
     * destZone = "PQ"; }
     */

    // destination
    Party recipient = new Party();
    Address recipientAddress = new Address(); // Destination information
    recipientAddress.setStreetLines(new String[] { customer.getCustomerStreetAddress() });
    recipientAddress.setCity(customer.getCustomerCity());
    recipientAddress.setStateOrProvinceCode(customerZoneName);
    recipientAddress.setPostalCode(
            com.salesmanager.core.util.ShippingUtil.trimPostalCode(customer.getCustomerPostalCode()));
    recipientAddress.setCountryCode(customerCountry.getCountryIsoCode2());

    recipient.setAddress(recipientAddress);
    requestedShipment.setRecipient(recipient);

    //
    Payment shippingChargesPayment = new Payment();
    shippingChargesPayment.setPaymentType(PaymentType.SENDER);
    requestedShipment.setShippingChargesPayment(shippingChargesPayment);

    // build packages

    RequestedPackage[] rpArray = new RequestedPackage[packages.size()];

    Iterator packagesIterator = packages.iterator();
    int i = 0;
    while (packagesIterator.hasNext()) {

        PackageDetail detail = (PackageDetail) packagesIterator.next();
        RequestedPackage rp = new RequestedPackage();

        Weight w = null;
        if (store.getWeightunitcode().equals(Constants.LB_WEIGHT_UNIT)) {
            w = new Weight(WeightUnits.LB, new BigDecimal(detail.getShippingWeight()));
        } else {
            w = new Weight(WeightUnits.KG, new BigDecimal(detail.getShippingWeight()));
        }

        Dimensions d = null;

        BigDecimal h = new BigDecimal(detail.getShippingHeight());
        h.setScale(2, BigDecimal.ROUND_UP);
        int ih = h.intValue();

        BigDecimal sw = new BigDecimal(detail.getShippingWeight());
        sw.setScale(2, BigDecimal.ROUND_UP);
        int isw = sw.intValue();

        BigDecimal sw2 = new BigDecimal(detail.getShippingWidth());
        sw2.setScale(2, BigDecimal.ROUND_UP);
        int isw2 = sw2.intValue();

        if (store.getSeizeunitcode().equals(Constants.INCH_SIZE_UNIT)) {
            d = new Dimensions(new NonNegativeInteger(String.valueOf(ih)),
                    new NonNegativeInteger(String.valueOf(isw)), new NonNegativeInteger(String.valueOf(isw2)),
                    LinearUnits.IN);
        } else {
            d = new Dimensions(new NonNegativeInteger(String.valueOf(ih)),
                    new NonNegativeInteger(String.valueOf(isw)), new NonNegativeInteger(String.valueOf(isw2)),
                    LinearUnits.CM);
        }

        rp.setWeight(w);
        // insurance
        // rp.setInsuredValue(new Money(store.getCurrency(), new
        // BigDecimal("100.00")));
        //
        rp.setDimensions(d);
        PackageSpecialServicesRequested pssr = new PackageSpecialServicesRequested();
        rp.setSpecialServicesRequested(pssr);

        rpArray[i] = rp;
        i++;

    }
    requestedShipment.setRequestedPackages(rpArray);

    requestedShipment.setPackageCount(new NonNegativeInteger(String.valueOf(packages.size())));
    requestedShipment.setRateRequestTypes(new RateRequestType[] { RateRequestType.ACCOUNT });
    requestedShipment.setPackageDetail(RequestedPackageDetailType.INDIVIDUAL_PACKAGES);
    request.setRequestedShipment(requestedShipment);

    //
    try {
        // Initialize the service
        RateServiceLocator service;
        RatePortType p;
        //
        service = new RateServiceLocator();

        // updateEndPoint(service);
        String endPointUrl = protocol + "://" + host + ":" + port + url;

        service.setRateServicePortEndpointAddress(endPointUrl);

        p = service.getRateServicePort();
        // This is the call to the web service passing in a RateRequest and
        // returning a RateReply
        RateReply reply = p.getRates(request); // Service call
        if (isResponseOk(reply.getHighestSeverity())) {
            returnColl = writeServiceOutput(displayQuoteDeliveryTime, reply, module, carrier, locale,
                    store.getCurrency());
        }
        printNotifications(store, reply.getNotifications());

    } catch (RuntimeException e) {
        e.printStackTrace();
        log.error(e);
    } catch (Exception ex) {
        log.error(ex);
    }

    return returnColl;
}

From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java

/**
 * sets the parameters for the colormap of an isoline
 *///from   www  . j  a  va2  s  .co  m
private static void configureLineSymbolizer(final SurfaceLineSymbolizer symbolizer, final BigDecimal minValue,
        final BigDecimal maxValue) throws FilterEvaluationException {
    final LineColorMap templateColorMap = symbolizer.getColorMap();
    final LineColorMap newColorMap = new LineColorMap_Impl();

    // retrieve stuff from template-entries
    final LineColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$
    final LineColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$
    final LineColorMapEntry fatEntry = templateColorMap.findEntry("fat", null); //$NON-NLS-1$

    final Color fromColor = fromEntry.getStroke().getStroke(null);
    final Color toColor = toEntry.getStroke().getStroke(null);
    final double opacity = fromEntry.getStroke().getOpacity(null);

    final double normalWidth = fromEntry.getStroke().getWidth(null);
    final double fatWidth = fatEntry.getStroke().getWidth(null);

    // defines which isolines are drawn with a fat line
    final double fatValue = fatEntry.getQuantity(null);
    // TODO: get setep / scale from quantity
    // get rounded values below min and above max (rounded by first decimal)
    // as a first try we will generate isolines using class steps of 0.1
    // later, the classes will be done by using user defined class steps.
    // for that we fill an array of calculated (later user defined values) from max to min
    final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR);
    final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING);

    final BigDecimal stepWidth = new BigDecimal(0.1).setScale(1, BigDecimal.ROUND_HALF_UP);
    final int numOfClasses = (maxDecimal.subtract(minDecimal).divide(stepWidth)).intValue() + 1;

    for (int currentClass = 0; currentClass < numOfClasses; currentClass++) {
        final double currentValue = minDecimal.doubleValue() + currentClass * stepWidth.doubleValue();

        Color lineColor;
        if (fromColor == toColor)
            lineColor = fromColor;
        else
            lineColor = interpolateColor(fromColor, toColor, currentClass, numOfClasses);

        final double strokeWidth;
        if (currentValue % fatValue == 0)
            strokeWidth = fatWidth;
        else
            strokeWidth = normalWidth;

        final Stroke stroke = StyleFactory.createStroke(lineColor, strokeWidth, opacity);

        final ParameterValueType label = StyleFactory.createParameterValueType("Isolinie " + currentClass); //$NON-NLS-1$
        final ParameterValueType quantity = StyleFactory.createParameterValueType(currentValue);

        final LineColorMapEntry colorMapEntry = new LineColorMapEntry_Impl(stroke, label, quantity);
        newColorMap.addColorMapClass(colorMapEntry);
    }

    symbolizer.setColorMap(newColorMap);
}

From source file:org.kuali.kfs.module.ar.businessobject.CustomerInvoiceDetail.java

/**
 * This method returns the invoice pre tax amount
 *
 * @return//w ww  .  ja  va2 s  .c  om
 */
public KualiDecimal getInvoiceItemPreTaxAmount() {
    if (ObjectUtils.isNotNull(invoiceItemUnitPrice) && ObjectUtils.isNotNull(invoiceItemQuantity)) {
        BigDecimal bd = invoiceItemUnitPrice.multiply(invoiceItemQuantity);
        bd = bd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
        return new KualiDecimal(bd);
    } else {
        return KualiDecimal.ZERO;
    }
}

From source file:de.forsthaus.webui.InitApplicationCtrl.java

/**
 * Add a new row to the grid.<br>//from  w  w  w.  ja v a 2  s.  com
 * 
 * @param rowParent
 * @param tableName
 * @param value
 */
private void addNewRow(Rows rowParent, String tableName, Object value) {

    Row row = new Row();

    Html html_TableName = new Html(tableName);
    html_TableName.setStyle("padding-left: 5px;");
    Div divKey = new Div();
    divKey.setAlign("left");
    divKey.appendChild(html_TableName);

    Html html_RecordCount = null;

    if (value instanceof BigDecimal) {
        BigDecimal myDec = (BigDecimal) value;
        myDec = myDec.setScale(2, BigDecimal.ROUND_HALF_UP);

        // Format the value to money
        NumberFormat formatter = new DecimalFormat("#,##0.00");
        String money = formatter.format(myDec);

        html_RecordCount = new Html(money);
    } else if (value instanceof Integer) {
        // Format the value
        NumberFormat formatter = new DecimalFormat("###,###.###");
        String formattedInteger = formatter.format(value);
        html_RecordCount = new Html(String.valueOf(value));
    } else
        html_RecordCount = new Html(String.valueOf(value));

    html_RecordCount.setStyle("padding-right: 5px;");
    Div divValue = new Div();
    divValue.setAlign("right");
    divValue.appendChild(html_RecordCount);

    row.appendChild(divKey);
    row.appendChild(divValue);
    row.setParent(rowParent);

}

From source file:de.forsthaus.webui.InitApplicationCtrl.java

/**
 * Add a new row to the grid.<br>//www. j a  v a  2  s.  c  o  m
 * 
 * @param rowParent
 * @param tableName
 * @param value
 * @param color
 */
private void addNewRow(Rows rowParent, String tableName, Object value, String color) {

    Row row = new Row();

    Html html_TableName = new Html(tableName);
    html_TableName.setStyle("padding-left: 5px; color: " + color + ";");
    Div divKey = new Div();
    divKey.setAlign("left");
    divKey.appendChild(html_TableName);

    Html html_RecordCount = null;

    if (value instanceof BigDecimal) {
        BigDecimal myDec = (BigDecimal) value;
        myDec = myDec.setScale(2, BigDecimal.ROUND_HALF_UP);

        // Format the value to money
        NumberFormat formatter = new DecimalFormat("#,##0.00");

        String money = formatter.format(myDec);

        html_RecordCount = new Html(money);
    } else if (value instanceof Integer) {
        // Format the value
        NumberFormat formatter = new DecimalFormat("###,###.###");
        String formattedInteger = formatter.format(value);
        html_RecordCount = new Html(String.valueOf(value));
    } else
        html_RecordCount = new Html(String.valueOf(value));

    html_RecordCount.setStyle("padding-right: 5px; color: " + color + ";");
    Div divValue = new Div();
    divValue.setAlign("right");
    divValue.appendChild(html_RecordCount);

    row.appendChild(divKey);
    row.appendChild(divValue);
    row.setParent(rowParent);

}

From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java

/**
 * Populates the consolidated demand information in CollectionIndexDetails
 *
 * @param waterChargedashBoardRequest//from  ww w  .  jav a  2  s  .  co  m
 * @param collectionIndexDetails
 */
public List<WaterChargeDashBoardResponse> getConsolidatedDemandInfo(
        final WaterChargeDashBoardRequest waterChargedashBoardRequest) {
    final List<WaterChargeDashBoardResponse> collectionIndexDetailsList = new ArrayList<>();
    final WaterChargeDashBoardResponse collectionIndexDetails = new WaterChargeDashBoardResponse();

    Date fromDate;
    Date toDate;
    /**
     * For fetching total demand between the date ranges if dates are sent
     * in the request, consider fromDate and toDate+1 , else calculate from
     * current year start date till current date+1 day
     */
    if (StringUtils.isNotBlank(waterChargedashBoardRequest.getFromDate())
            && StringUtils.isNotBlank(waterChargedashBoardRequest.getToDate())) {
        fromDate = DateUtils.getDate(waterChargedashBoardRequest.getFromDate(), "yyyy-MM-dd");
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(waterChargedashBoardRequest.getToDate(), "yyyy-MM-dd"), 1);
    } else {
        fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate();
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }
    Long startTime = System.currentTimeMillis();
    final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(waterChargedashBoardRequest);
    Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by getTotalDemandBasedOnInputFilters() is (millisecs) : " + timeTaken);
    startTime = System.currentTimeMillis();
    final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
    collectionIndexDetails.setTotalDmd(totalDemand);

    // Proportional Demand = (totalDemand/12)*noOfmonths
    final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
            .multiply(BigDecimal.valueOf(noOfMonths));
    collectionIndexDetails.setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP));

    // performance = (current year tilldate collection * 100)/(proportional
    // demand)
    collectionIndexDetails.setPerformance(
            collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));
    // variance = ((currentYearCollection -
    // lastYearCollection)*100)/lastYearCollection
    BigDecimal variation;
    if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
        variation = WaterTaxConstants.BIGDECIMAL_100;
    else
        variation = collectionIndexDetails.getCurrentYearTillDateColl()
                .subtract(collectionIndexDetails.getLastYearTillDateColl())
                .multiply(WaterTaxConstants.BIGDECIMAL_100)
                .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
    collectionIndexDetails.setLastYearVar(variation);
    timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(
                "Time taken for setting values in getConsolidatedDemandInfo() is (millisecs) : " + timeTaken);
    final ErrorDetails errorDetails = new ErrorDetails();
    errorDetails.setErrorCode(WaterTaxConstants.THIRD_PARTY_ERR_CODE_SUCCESS);
    errorDetails.setErrorMessage(WaterTaxConstants.THIRD_PARTY_ERR_MSG_SUCCESS);
    collectionIndexDetails.setErrorDetails(errorDetails);
    collectionIndexDetailsList.add(collectionIndexDetails);
    return collectionIndexDetailsList;
}

From source file:org.egov.ptis.web.controller.masters.taxrates.TaxRatesController.java

private void addTotalTaxHeadsToModel(Model model) {
    BigDecimal totRsdTax = BigDecimal.ZERO;
    BigDecimal totNRsdTax = BigDecimal.ZERO;
    BigDecimal eduTax = BigDecimal.ZERO;
    for (EgDemandReasonDetails drd : taxRatesService.getTaxRates()) {
        if (drd.getEgDemandReasonMaster().getCode().equals(TOTAL_TAX_RESD))
            totRsdTax = drd.getPercentage();
        if (drd.getEgDemandReasonMaster().getCode().equals(TOTAL_TAX_NONRESD))
            totNRsdTax = drd.getPercentage();
        if (drd.getEgDemandReasonMaster().getCode().equals(EDUCATIONAL_TAX))
            eduTax = drd.getPercentage();
    }//from   w  w w .  jav a 2 s. c o  m
    totRsdTax = totRsdTax.add(eduTax);
    totNRsdTax = totNRsdTax.add(eduTax);
    model.addAttribute("genTaxResd", totRsdTax.setScale(2, BigDecimal.ROUND_CEILING));
    model.addAttribute("genTaxNonResd", totNRsdTax.setScale(2, BigDecimal.ROUND_CEILING));
}