Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java

public BigDecimal getTotalSellPriceByEntrustList(List<TbFixEntrust> tbfixEntrustList) {
    if (tbfixEntrustList == null || tbfixEntrustList.size() == 0)
        return new BigDecimal("0.00");

    String entrustIds = "";
    for (TbFixEntrust tbFixEntrust : tbfixEntrustList) {
        entrustIds += tbFixEntrust.getId() + ",";
    }// www .j a v  a 2 s. c o m
    entrustIds = tbfixEntrustList.size() > 0 ? entrustIds.substring(0, entrustIds.length() - 1) : null;

    if (entrustIds != null) {

        StringBuilder sql = new StringBuilder();
        sql.append("select sum(m.price*m.part_quantity) from tb_fix_entrust fe , tb_maintain_part_content m ");
        sql.append(" where fe.id = m.entrust_id and m.is_free = 1 and m.is_confirm not in (8000)");
        sql.append(" and fe.id in ( " + entrustIds + ")");
        sql.append(" union all");
        sql.append(
                " select sum(sod.price*sod.quantity) from tb_fix_entrust fe , tm_stock_out so  , tm_stockout_detail sod");
        sql.append(
                " where fe.entrust_code = so.trust_bill  and sod.is_free = 1 and so.id = sod.stockout_id and so.is_confirm not in (8000)");
        sql.append(" and fe.id in ( " + entrustIds + ")");

        List<BigDecimal> objList = tbFixEntrustDao.findByOriginSql(sql.toString(), null);

        BigDecimal wxSellPrice = objList.get(0) != null ? new BigDecimal(objList.get(0).toString())
                : new BigDecimal("0.00");

        BigDecimal xsSellPrice = objList.get(1) != null ? new BigDecimal(objList.get(1).toString())
                : new BigDecimal("0.00");

        BigDecimal result = wxSellPrice.add(xsSellPrice).divide(new BigDecimal("1.00"), 2,
                BigDecimal.ROUND_HALF_UP);

        return result;
    }
    return new BigDecimal("0.00");
}

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

public List<WaterChargeConnectionTypeResponse> getMonthwiseCollectionDetailsForConnectionType(
        final WaterChargeDashBoardRequest collectionDetailsRequest) {
    final List<WaterChargeConnectionTypeResponse> collTrendsList = new ArrayList<>();
    WaterChargeConnectionTypeResponse collTrend;
    Date fromDate;/*from   w  w  w  . j  a  v a  2  s.  com*/
    Date toDate;
    Date dateForMonth;
    String[] dateArr;
    Integer month;
    Sum aggregateSum;
    final CFinancialYear financialYear = cFinancialYearService.getCurrentFinancialYear();
    Date finYearStartDate = financialYear.getStartingDate();
    Date finYearEndDate = financialYear.getEndingDate();
    final Map<Integer, String> monthValuesMap = DateUtils.getAllMonthsWithFullNames();
    String monthName;
    final List<Map<String, BigDecimal>> yearwiseMonthlyCollList = new ArrayList<>();
    final List<Map<String, BigDecimal>> yearwiseMonthlyCommercialCollList = new ArrayList<>();
    Map<String, BigDecimal> monthwiseColl;
    Map<String, BigDecimal> monthwiseColl2;
    /**
     * For month-wise collections 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(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = DateUtils.startOfDay(financialYear.getStartingDate());
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }

    final Long startTime = System.currentTimeMillis();
    for (int count = 0; count <= 2; count++) {
        monthwiseColl = new LinkedHashMap<>();
        final Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYearsTemp(collectionDetailsRequest,
                fromDate, toDate, WaterTaxConstants.RESIDENTIALCONNECTIONTYPEFORDASHBOARD);
        final Aggregations collAggrComm = getMonthwiseCollectionsForConsecutiveYearsTemp(
                collectionDetailsRequest, fromDate, toDate,
                WaterTaxConstants.COMMERCIALCONNECTIONTYPEFORDASHBOARD);

        if (collAggr != null) {
            final Histogram dateaggs = collAggr.get(AGGR_DATE);
            for (final Histogram.Bucket entry : dateaggs.getBuckets()) {
                dateArr = entry.getKeyAsString().split("T");
                dateForMonth = DateUtils.getDate(dateArr[0], DATE_FORMAT_YYYYMMDD);
                month = Integer.valueOf(dateArr[0].split("-", 3)[1]);
                monthName = monthValuesMap.get(month);
                aggregateSum = entry.getAggregations().get("current_total");
                // If the total amount is greater than 0 and the month
                // belongs
                // to respective financial year, add values to the map
                if (DateUtils.between(dateForMonth, finYearStartDate, finYearEndDate)
                        && BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                                .compareTo(BigDecimal.ZERO) > 0)
                    monthwiseColl.put(monthName,
                            BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
            }
        }
        yearwiseMonthlyCollList.add(monthwiseColl);
        monthwiseColl2 = new LinkedHashMap<>();

        if (collAggrComm != null) {
            final Histogram commdateaggs = collAggrComm.get(AGGR_DATE);
            for (final Histogram.Bucket entry : commdateaggs.getBuckets()) {
                dateArr = entry.getKeyAsString().split("T");
                dateForMonth = DateUtils.getDate(dateArr[0], DATE_FORMAT_YYYYMMDD);
                month = Integer.valueOf(dateArr[0].split("-", 3)[1]);
                monthName = monthValuesMap.get(month);
                aggregateSum = entry.getAggregations().get("current_total");
                // If the total amount is greater than 0 and the month
                // belongs
                // to respective financial year, add values to the map
                if (DateUtils.between(dateForMonth, finYearStartDate, finYearEndDate)
                        && BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                                .compareTo(BigDecimal.ZERO) > 0)
                    monthwiseColl2.put(monthName,
                            BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
            }
        }
        yearwiseMonthlyCommercialCollList.add(monthwiseColl2);

        /**
         * If dates are passed in request, get result for the date range,
         * else get results for entire financial year
         */
        if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
                && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
            fromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1);
            toDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1);
        } else {
            fromDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1);
            toDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1);
        }
        finYearStartDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1);
        finYearEndDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1);
    }
    final Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(
                "Time taken by getMonthwiseCollectionsForConsecutiveYears() for 3 consecutive years is (millisecs): "
                        + timeTaken);

    /**
     * If dates are passed in request, get result for the date range, else
     * get results for all 12 months
     */
    if (StringUtils.isBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isBlank(collectionDetailsRequest.getToDate()))
        for (final Map.Entry<Integer, String> entry : DateUtils.getAllFinancialYearMonthsWithFullNames()
                .entrySet()) {
            collTrend = new WaterChargeConnectionTypeResponse();
            collTrend.setMonth(entry.getValue());
            collTrend.setCurrentYearResidentialColl(
                    yearwiseMonthlyCollList.get(0).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(0).get(collTrend.getMonth()));
            collTrend.setLastYearResidentialColl(
                    yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPreviousYearResidentialColl(
                    yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()));

            collTrend.setCurrentYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(0).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(0).get(collTrend.getMonth()));
            collTrend.setLastYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPreviousYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(2).get(collTrend.getMonth()));
            collTrendsList.add(collTrend);
        }
    else
        for (final Map.Entry<String, BigDecimal> entry : yearwiseMonthlyCollList.get(0).entrySet()) {
            collTrend = new WaterChargeConnectionTypeResponse();
            collTrend.setMonth(entry.getKey());
            collTrend.setCurrentYearResidentialColl(entry.getValue());
            collTrend.setLastYearResidentialColl(
                    yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPreviousYearResidentialColl(
                    yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()));

            collTrend.setCurrentYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(0).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(0).get(collTrend.getMonth()));
            collTrend.setLastYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPreviousYearCommercialColl(
                    yearwiseMonthlyCommercialCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCommercialCollList.get(2).get(collTrend.getMonth()));
            collTrendsList.add(collTrend);
        }
    return collTrendsList;
}

From source file:com.cssweb.android.trade.util.TradeUtil.java

/**
 * ??//www .j  a  va2 s .  c  om
 */
public static String formatNum(String str, int len) {
    if (str == null)
        return "";
    int flag = 1;
    if (str.charAt(0) == '-' && str.charAt(1) == '.') {
        str = str.replace("-.", "-0.");
        flag = -1;
    }
    if (str.charAt(0) == '.')
        str = "0" + str;
    if (len < 0)
        len = 0;
    BigDecimal small = new BigDecimal("0");
    BigDecimal big = new BigDecimal("0");
    if (("0").equals(str) && len == 0)
        return "0";
    if (str.indexOf(".") != -1) {
        String[] ary = str.split("\\.");
        big = BigDecimal.valueOf(Double.parseDouble(ary[0]));
        small = BigDecimal.valueOf(Double.parseDouble("0." + ary[1]));
        small = small.setScale(len > 0 ? len : 1, BigDecimal.ROUND_HALF_UP);
        if (str.charAt(0) == '-') {
            return big.subtract(small).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP)
                    .toString();
        }
        return big.add(small).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP).toString();
    } else {
        return new BigDecimal(str).multiply(new BigDecimal(flag)).setScale(len, BigDecimal.ROUND_HALF_UP)
                .toString();
    }
}

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

/**
 * Add the information about the costs of the positions.
 *
 * @param _parameter        Parameter as passed from the eFaps API
 * @param _date             Date the cost will be search for
 * @param _doc              Instance of the Document the form was opened for
 * @return html snipplet/*from  w  w w  . j av  a 2  s  .  c o  m*/
 * @throws EFapsException on error
 */
protected StringBuilder getCostInformation(final Parameter _parameter, final DateTime _date,
        final DocumentInfo _doc) throws EFapsException {
    final StringBuilder html = new StringBuilder();
    if (_doc.isStockDoc()) {
        boolean costValidated = true;
        final Map<?, ?> props = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
        final boolean script = !"true".equalsIgnoreCase((String) props.get("noScript"));
        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameter);
        final RateInfo rate = evaluateRate(_parameter, periodInst, _date == null ? new DateTime() : _date,
                null);
        _doc.setRateInfo(rate);

        html.append("<table>");
        final QueryBuilder queryBldr = new QueryBuilder(CISales.PositionAbstract);
        queryBldr.addWhereAttrEqValue(CISales.PositionAbstract.DocumentAbstractLink,
                _doc.getInstance().getId());
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CISales.PositionAbstract.Quantity, CISales.PositionAbstract.UoM);
        final SelectBuilder sel = new SelectBuilder().linkto(CISales.PositionAbstract.Product);
        final SelectBuilder oidSel = new SelectBuilder(sel).oid();
        final SelectBuilder nameSel = new SelectBuilder(sel).attribute(CIProducts.ProductAbstract.Name);
        final SelectBuilder descSel = new SelectBuilder(sel).attribute(CIProducts.ProductAbstract.Description);
        multi.addSelect(oidSel, nameSel, descSel);
        multi.execute();
        boolean first = true;
        BigDecimal total = BigDecimal.ZERO;
        while (multi.next()) {
            final Instance prodInst = Instance.get(multi.<String>getSelect(oidSel));
            if (first) {
                first = false;
                html.append("<tr>").append("<th>")
                        .append(getLabel(multi.getCurrentInstance(), CISales.PositionAbstract.Quantity))
                        .append("</th>").append("<th>")
                        .append(getLabel(multi.getCurrentInstance(), CISales.PositionAbstract.UoM))
                        .append("</th>").append("<th>")
                        .append(getLabel(prodInst, CIProducts.ProductAbstract.Name)).append("</th>")
                        .append("<th>").append(getLabel(prodInst, CIProducts.ProductAbstract.Description))
                        .append("</th>").append("<th>")
                        .append(DBProperties.getProperty(CIProducts.ProductCost.getType().getName()
                                + "/" + CIProducts.ProductCost.Price.name + ".Label"))
                        .append("</th>").append("<th>")
                        .append(DBProperties.getProperty(CIProducts.ProductCost.getType().getName() + "/"
                                + CIProducts.ProductCost.CurrencyLink.name + ".Label"))
                        .append("</th>").append("<tr>");
            }
            html.append("<tr>");

            final BigDecimal quantity = multi.<BigDecimal>getAttribute(CISales.PositionAbstract.Quantity);
            final UoM uom = Dimension.getUoM(multi.<Long>getAttribute(CISales.PositionAbstract.UoM));
            html.append("<td>").append(quantity).append("</td>").append("<td>").append(uom.getName())
                    .append("</td>").append("<td>").append(multi.<String>getSelect(nameSel)).append("</td>")
                    .append("<td>").append(multi.<String>getSelect(descSel)).append("</td>");

            final QueryBuilder costQueryBuilder = new QueryBuilder(CIProducts.ProductCost);
            costQueryBuilder.addWhereAttrEqValue(CIProducts.ProductCost.ProductLink, prodInst.getId());
            costQueryBuilder.addWhereAttrLessValue(CIProducts.ProductCost.ValidFrom,
                    _date == null ? new DateTime() : _date.plusMinutes(1));
            costQueryBuilder.addWhereAttrGreaterValue(CIProducts.ProductCost.ValidUntil,
                    _date == null ? new DateTime() : _date.minusMinutes(1));
            costQueryBuilder.addOrderByAttributeDesc(CIProducts.ProductCost.ID);
            final InstanceQuery query = costQueryBuilder.getQuery();
            query.setLimit(1);
            query.executeWithoutAccessCheck();
            if (query.next()) {
                final PrintQuery print = new PrintQuery(query.getCurrentValue());
                print.addAttribute(CIProducts.ProductCost.Price);
                final SelectBuilder currSel = new SelectBuilder().linkto(CIProducts.ProductCost.CurrencyLink)
                        .instance();
                print.addSelect(currSel);
                print.executeWithoutAccessCheck();
                final BigDecimal price = print.<BigDecimal>getAttribute(CIProducts.ProductCost.Price);
                final Instance currInst = print.<Instance>getSelect(currSel);

                final RateInfo rateTmp = evaluateRate(_parameter, periodInst,
                        _date == null ? new DateTime() : _date, currInst);

                final BigDecimal cost = quantity.multiply(new BigDecimal(uom.getNumerator()))
                        .divide(new BigDecimal(uom.getDenominator())).multiply(price);
                html.append("<td>").append(NumberFormatter.get().getTwoDigitsFormatter().format(price))
                        .append("</td>").append("<td>").append(rateTmp.getCurrencyInstObj().getSymbol())
                        .append("</td>");

                if (script) {
                    analyzeProduct(_doc, true, prodInst, cost, rate,
                            CIAccounting.AccountBalanceSheetAsset2ProductClass,
                            CIAccounting.AccountBalanceSheetAsset);
                    analyzeProduct(_doc, false, prodInst, cost, rate,
                            CIAccounting.AccountIncomeStatementExpenses2ProductClass,
                            CIAccounting.AccountIncomeStatementExpenses);
                }
                total = total.add(cost.setScale(12, BigDecimal.ROUND_HALF_UP).divide(rateTmp.getRate(),
                        BigDecimal.ROUND_HALF_UP));
            } else {
                html.append("<td></td>").append("<td></td>");
                if (costValidated) {
                    costValidated = false;
                }
            }
            html.append("</tr>");
        }
        html.append("<tr>").append("<td colspan=4></td><td>")
                .append(NumberFormatter.get().getTwoDigitsFormatter().format(total))
                .append("<input type=\"hidden\" name=\"amountExternal\" value=\"").append(total).append("\"/>")
                .append("</td>").append("<td>").append(rate.getCurrencyInstObj().getSymbol())
                .append("<input type=\"hidden\" name=\"currencyExternal\" value=\"")
                .append(rate.getCurrencyInstance().getId()).append("\"/>").append("</td>").append("<tr>")
                .append("</table>");
        _doc.setCostValidated(costValidated);
        _doc.setAmount(total);
    }
    return html;
}

From source file:coffeshop.PaymentPage.java

private void generateQR(String btcPay) throws Exception {
    BigDecimal dollar = new BigDecimal(btcPay);
    BigDecimal btcPriceIndex = btcPriceIndex();
    BigDecimal btc = dollar.divide(btcPriceIndex, 5, BigDecimal.ROUND_HALF_UP);
    byte[] imageInByte;
    BufferedImage originalImage = ImageIO.read(new File("src/ImageRes/QR.jpg"));
    String details = "bitcoin:12nAq7bJSkKFxJYaHjhjfPAaZ6sXgLqBJ7?amount=" + btc;
    QRCode.from(details).withSize(125, 125).file();
    QRCode.from(details).withSize(125, 125).stream();
    ByteArrayOutputStream out = QRCode.from(details).to(ImageType.JPG).stream();
    ImageIO.write(originalImage, "jpg", out);
    out.flush();//  w ww  . j  a v  a 2 s .  c o m
    imageInByte = out.toByteArray();
    out.close();
    InputStream in = new ByteArrayInputStream(imageInByte);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, "jpg", new File("src/ImageRes/QR.jpg"));
}

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

/**
 * Get the script to get the Prices for the Products.
 *
 * @param _parameter        Parameter as passed from the eFaps API
 * @param _doc              Instance of the Document the form was opened for
 * @throws EFapsException on error/*from  ww w.ja va 2 s .  co  m*/
 */
protected void getPriceInformation(final Parameter _parameter, final DocumentInfo _doc) throws EFapsException {
    final QueryBuilder queryBldr = new QueryBuilder(CISales.PositionAbstract);
    queryBldr.addWhereAttrEqValue(CISales.PositionAbstract.DocumentAbstractLink, _doc.getInstance().getId());
    final MultiPrintQuery multi = queryBldr.getPrint();
    final SelectBuilder selTaxInst = new SelectBuilder().linkto(CISales.PositionSumAbstract.Tax).instance();
    final SelectBuilder selProdInst = new SelectBuilder().linkto(CISales.PositionAbstract.Product).instance();
    multi.addSelect(selTaxInst, selProdInst);
    multi.addAttribute(CISales.PositionSumAbstract.NetPrice, CISales.PositionSumAbstract.CrossPrice,
            CISales.PositionSumAbstract.Rate);
    multi.execute();
    final Instance period = new Period().evaluateCurrentPeriod(_parameter);
    while (multi.next()) {
        final BigDecimal net = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.NetPrice);
        final BigDecimal cross = multi.<BigDecimal>getAttribute(CISales.PositionSumAbstract.CrossPrice);
        final Object[] ratePos = multi.<Object[]>getAttribute(CISales.PositionSumAbstract.Rate);
        final BigDecimal newRatepos = ((BigDecimal) ratePos[0]).divide((BigDecimal) ratePos[1], 12,
                BigDecimal.ROUND_HALF_UP);
        final BigDecimal taxAmount = cross.subtract(net).multiply(newRatepos);
        final BigDecimal prodAmount = net.multiply(newRatepos);
        analyzeTax(_doc, false, multi.<Instance>getSelect(selTaxInst), taxAmount);
        final RateInfo rate = evaluateRate(_parameter, period, _doc.getDate(), _doc.getRateCurrInst());
        analyzeProduct(_doc, false, multi.<Instance>getSelect(selProdInst), prodAmount, rate,
                CIAccounting.AccountIncomeStatementRevenue2ProductClass,
                CIAccounting.AccountIncomeStatementRevenue);
    }
}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * Prepare list of TaxPayerDetails for each bill collector by summing up the values in each ward for the respective bil
 * collector/*from  ww  w  .  j a va2s  .c o m*/
 *
 * @param collectionDetailsRequest
 * @param billCollectorWiseMap
 * @param billCollectorWiseTaxPayerDetails
 */
private void prepareTaxersInfoForBillCollectors(final CollectionDetailsRequest collectionDetailsRequest,
        final Map<String, List<TaxPayerDetails>> billCollectorWiseMap,
        final List<TaxPayerDetails> billCollectorWiseTaxPayerDetails) {
    BigDecimal cytdColl;
    BigDecimal lytdColl;
    BigDecimal cytdDmd;
    BigDecimal totalDmd;
    TaxPayerDetails taxPayerDetails;
    String[] userNameNumberArr;
    for (final Entry<String, List<TaxPayerDetails>> entry : billCollectorWiseMap.entrySet()) {
        taxPayerDetails = new TaxPayerDetails();
        cytdColl = BigDecimal.ZERO;
        lytdColl = BigDecimal.ZERO;
        cytdDmd = BigDecimal.ZERO;
        totalDmd = BigDecimal.ZERO;
        userNameNumberArr = entry.getKey().split("~");
        for (final TaxPayerDetails taxPayer : entry.getValue()) {
            totalDmd = totalDmd.add(taxPayer.getTotalDmd() == null ? BigDecimal.ZERO : taxPayer.getTotalDmd());
            cytdColl = cytdColl.add(taxPayer.getCytdColl() == null ? BigDecimal.ZERO : taxPayer.getCytdColl());
            cytdDmd = cytdDmd.add(taxPayer.getCytdDmd() == null ? BigDecimal.ZERO : taxPayer.getCytdDmd());
            lytdColl = lytdColl.add(taxPayer.getLytdColl() == null ? BigDecimal.ZERO : taxPayer.getLytdColl());
        }

        if (DASHBOARD_GROUPING_BILLCOLLECTORWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails
                    .setBillCollector(userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails
                    .setBillCollMobNo(userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setBillCollectorCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        } else if (DASHBOARD_GROUPING_REVENUEINSPECTORWISE
                .equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails.setRevenueInspector(
                    userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails.setRevInspectorMobNo(
                    userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setRevenueInspectorCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        } else if (DASHBOARD_GROUPING_REVENUEOFFICERWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) {
            taxPayerDetails
                    .setRevenueOfficer(userNameNumberArr.length > 0 ? userNameNumberArr[0] : StringUtils.EMPTY);
            taxPayerDetails.setRevOfficerMobNo(
                    userNameNumberArr.length > 1 ? userNameNumberArr[1] : StringUtils.EMPTY);
            taxPayerDetails.setRevenueOfficerCode(
                    userNameNumberArr.length > 2 ? userNameNumberArr[2] : StringUtils.EMPTY);
        }

        taxPayerDetails.setRegionName(collectionDetailsRequest.getRegionName());
        taxPayerDetails.setDistrictName(collectionDetailsRequest.getDistrictName());
        taxPayerDetails.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        taxPayerDetails.setCytdColl(cytdColl);
        taxPayerDetails.setCytdDmd(cytdDmd);
        taxPayerDetails.setCytdBalDmd(cytdDmd.subtract(cytdColl));
        taxPayerDetails.setTotalDmd(totalDmd);
        taxPayerDetails.setLytdColl(lytdColl);
        if (cytdDmd.compareTo(BigDecimal.ZERO) > 0)
            taxPayerDetails.setAchievement(
                    cytdColl.multiply(BIGDECIMAL_100).divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP));
        if (lytdColl.compareTo(BigDecimal.ZERO) == 0)
            taxPayerDetails.setLyVar(BIGDECIMAL_100);
        else
            taxPayerDetails.setLyVar(cytdColl.subtract(lytdColl).multiply(BIGDECIMAL_100).divide(lytdColl, 1,
                    BigDecimal.ROUND_HALF_UP));

        billCollectorWiseTaxPayerDetails.add(taxPayerDetails);
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = "/{productCode}/addproductcurrentcharges", method = RequestMethod.GET)
public String addProductCurrentCharges(@PathVariable String productCode, ModelMap map) {
    logger.debug("### addProductCurrentCharges method starting...");

    Product product = productService.locateProductByCode(productCode);
    List<CurrencyValue> currencyValueList = currencyValueService.listActiveCurrencies();
    ProductForm productForm = new ProductForm(product);
    productForm.setCurrencyPresicion(/*  www.  j a va2s .  co  m*/
            Integer.parseInt(config.getValue(Names.com_citrix_cpbm_portal_appearance_currency_precision)));
    for (CurrencyValue cv : currencyValueList) {
        ProductCharge charge = new ProductCharge();
        // TODO: a configuration for scale (incase we change the scale in db, this wont get changed)
        charge.setPrice(BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP));
        charge.setProduct(product);
        charge.setCurrencyValue(cv);
        productForm.addProductCharges(charge);
    }
    map.addAttribute("productForm", productForm);

    logger.debug("### addProductCurrentCharges method ending...");
    return "add.product.current.charges";
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

private void setDemandAmountsForTableData(String name, CollTableData collIndData, BigDecimal totalAssessments,
        BigDecimal currentYearTotalDemand, int noOfMonths, Map<String, BigDecimal> totalDemandMap) {
    BigDecimal variance;/*  w  w w.  j  a  v a2s .c o  m*/
    // Proportional Demand = (totalDemand/12)*noOfmonths
    BigDecimal cytdDmd = (currentYearTotalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP))
            .multiply(BigDecimal.valueOf(noOfMonths));
    collIndData.setCytdDmd(cytdDmd);
    if (cytdDmd != BigDecimal.valueOf(0)) {
        BigDecimal balance = cytdDmd.subtract(collIndData.getCytdColl());
        BigDecimal performance = (collIndData.getCytdColl().multiply(PropertyTaxConstants.BIGDECIMAL_100))
                .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP);
        collIndData.setPerformance(performance);
        collIndData.setCytdBalDmd(balance);
    }
    collIndData.setTotalDmd(totalDemandMap.get(name) == null ? BigDecimal.ZERO : totalDemandMap.get(name));
    collIndData.setDayTargetDemand(collIndData.getTotalDmd().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : collIndData.getTotalDmd().divide(new BigDecimal("365"), 0, BigDecimal.ROUND_HALF_UP));
    collIndData.setTotalAssessments(totalAssessments);
    // variance = ((currentYearCollection - lastYearCollection)*100)/lastYearCollection
    if (collIndData.getLytdColl().compareTo(BigDecimal.ZERO) == 0)
        variance = PropertyTaxConstants.BIGDECIMAL_100;
    else
        variance = ((collIndData.getCytdColl().subtract(collIndData.getLytdColl()))
                .multiply(PropertyTaxConstants.BIGDECIMAL_100)).divide(collIndData.getLytdColl(), 1,
                        BigDecimal.ROUND_HALF_UP);
    collIndData.setLyVar(variance);
}

From source file:com.nimrodtechs.ipc.ZeroMQRmiClient.java

@Override
public String listCallMetrics() {
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, CallingMetric> entry : callingMetrics.entrySet()) {
        if (entry.getValue().callCount.get() > 0) {
            BigDecimal avgTrip = new BigDecimal(
                    entry.getValue().cummulativeRoundTripTime.get() / entry.getValue().callCount.get())
                            .setScale(3, BigDecimal.ROUND_HALF_UP).movePointLeft(6)
                            .setScale(6, BigDecimal.ROUND_HALF_UP);
            BigDecimal avgServ = new BigDecimal(
                    entry.getValue().cummulativeServerExecutionTime.get() / entry.getValue().callCount.get())
                            .setScale(3, BigDecimal.ROUND_HALF_UP).movePointLeft(6)
                            .setScale(6, BigDecimal.ROUND_HALF_UP);
            sb.append(entry.getValue().currentServiceAndMethodName + " " + entry.getValue().callCount.get()
                    + " avgTrip " + avgTrip.toPlainString() + " avgSerX " + avgServ.toPlainString()
                    + " minTrip "
                    + new BigDecimal(entry.getValue().minRoundTripTime)
                            .movePointLeft(6).setScale(6, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + " maxTrip "
                    + new BigDecimal(entry.getValue().maxRoundTripTime)
                            .movePointLeft(6).setScale(6, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + " minSerX "
                    + new BigDecimal(entry.getValue().minServerExecutionTime).movePointLeft(6)
                            .setScale(6, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + " maxSerX " + new BigDecimal(entry.getValue().maxServerExecutionTime).movePointLeft(6)
                            .setScale(6, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + "\n");
        }/*from   www  .j  av a  2  s  .c o m*/
    }
    return sb.toString();
}