Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor, MathContext mc) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , with rounding according to the context settings.

Usage

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Divide and round.//w  w w.  ja v a2 s .  co m
 *
 * @param x The numerator
 * @param y The denominator
 * @return the divided x/y
 */
static public BigDecimal divideRound(final BigDecimal x, final BigDecimal y) {
    /* The estimation of the relative error in the result is |err(y)/y|+|err(x)/x|
     */
    MathContext mc = new MathContext(Math.min(x.precision(), y.precision()));

    return x.divide(y, mc);

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.scholarship.utl.report.StudentLine.java

public Boolean getStudentHadPerformanceLastYear() {
    BigDecimal numberOfApprovedEctsOneYearAgo = getNumberOfApprovedEctsOneYearAgo();
    BigDecimal numberOfEnrolledEctsOneYearAgo = getNumberOfEnrolledEctsOneYearAgo();

    if (numberOfEnrolledEctsOneYearAgo.compareTo(BigDecimal.ZERO) == 0) {
        return false;
    }//w w w.j  a v a 2 s .co  m

    BigDecimal average = numberOfApprovedEctsOneYearAgo.divide(numberOfEnrolledEctsOneYearAgo,
            RoundingMode.HALF_EVEN);
    average.setScale(2);

    return average.compareTo(new BigDecimal(0.5f)) >= 0;
}

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

/**
 * @param _parameter Parameter as passed by the eFasp API
 * @return new Return/*from ww w  .  j a v a  2s  .  com*/
 * @throws EFapsException on error
 */
public Return createGainLoss4SimpleAccount(final Parameter _parameter) throws EFapsException {
    final PrintQuery printPer = new PrintQuery(_parameter.getInstance());
    final SelectBuilder selCurrInst = SelectBuilder.get().linkto(CIAccounting.Period.CurrencyLink).instance();
    printPer.addSelect(selCurrInst);
    printPer.addAttribute(CIAccounting.Period.FromDate, CIAccounting.Period.CurrencyLink);
    printPer.execute();
    final DateTime dateFrom = printPer.<DateTime>getAttribute(CIAccounting.Period.FromDate);
    final Instance currencyInst = printPer.<Instance>getSelect(selCurrInst);

    final String[] relOIDs = (String[]) Context.getThreadContext()
            .getSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.transactionDate.name));
    final DateTime dateEx = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.exchangeDate.name));
    Insert insert = null;
    BigDecimal totalSum = BigDecimal.ZERO;

    for (final String oid : relOIDs) {
        Instance tarCurInst = null;
        final Instance relInst = Instance.get(oid);
        final PrintQuery print = new PrintQuery(relInst);
        final SelectBuilder selAccount = new SelectBuilder()
                .linkto(CIAccounting.AccountConfigSimple2Period.FromLink).oid();
        print.addSelect(selAccount);
        print.addAttribute(CIAccounting.AccountConfigSimple2Period.IsSale);
        if (print.execute()) {
            final Instance instAcc = Instance.get(print.<String>getSelect(selAccount));
            final boolean isSale = print.<Boolean>getAttribute(CIAccounting.AccountConfigSimple2Period.IsSale);
            final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction);
            attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink, _parameter.getInstance());
            attrQuerBldr.addWhereAttrGreaterValue(CIAccounting.Transaction.Date, dateFrom.minusMinutes(1));
            attrQuerBldr.addWhereAttrLessValue(CIAccounting.Transaction.Date, dateTo.plusDays(1));
            final AttributeQuery attrQuery = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

            final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
            queryBldr.addWhereAttrEqValue(CIAccounting.TransactionPositionAbstract.AccountLink, instAcc);
            queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery);
            final MultiPrintQuery multi = queryBldr.getPrint();
            final SelectBuilder selTRInst = SelectBuilder.get()
                    .linkto(CIAccounting.TransactionPositionAbstract.RateCurrencyLink).instance();
            multi.addSelect(selTRInst);
            multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                    CIAccounting.TransactionPositionAbstract.RateAmount);
            BigDecimal gainlossSum = BigDecimal.ZERO;
            multi.execute();
            while (multi.next()) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = multi.<Instance>getSelect(selTRInst);
                final BigDecimal rate = evaluateRate(_parameter, dateEx, currencyInst, targetCurrInst, isSale);
                final BigDecimal newAmount = oldRateAmount.divide(rate, BigDecimal.ROUND_HALF_UP);

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currencyInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                    tarCurInst = targetCurrInst;
                } else {
                    gainloss = newAmount;
                }
                gainlossSum = gainlossSum.add(gainloss);
            }
            totalSum = totalSum.add(gainlossSum);

            final Map<String, String[]> map = validateInfo(_parameter, gainlossSum);
            final String[] accs = map.get("accs");
            final String[] check = map.get("check");

            if (checkAccounts(accs, 0, check).length() > 0) {
                if (gainlossSum.compareTo(BigDecimal.ZERO) != 0) {
                    final String[] accOids = map.get("accountOids");
                    if (insert == null) {
                        final String descr = DBProperties.getFormatedDBProperty(
                                Recalculate.class.getName() + ".gainLoss4SimpleAccountTransDesc",
                                dateTo.toDate());
                        insert = new Insert(CIAccounting.Transaction);
                        insert.add(CIAccounting.Transaction.Description, descr);
                        insert.add(CIAccounting.Transaction.Date, dateTo);
                        insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance());
                        insert.add(CIAccounting.Transaction.Status,
                                Status.find(CIAccounting.TransactionStatus.Open));
                        insert.execute();
                    }

                    Insert insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                    insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getInstance());
                    if (gainlossSum.signum() > 0) {
                        insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                Instance.get(accOids[0]));
                    } else {
                        insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc);
                    }
                    insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainlossSum.abs().negate());
                    insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount, BigDecimal.ZERO);
                    insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currencyInst);
                    insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, tarCurInst);
                    insertPos.add(CIAccounting.TransactionPositionDebit.Rate,
                            new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                    insertPos.execute();

                    insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                    insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getInstance());
                    if (gainlossSum.signum() > 0) {
                        insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc);
                    } else {
                        insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                Instance.get(accOids[0]));
                    }
                    insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainlossSum.abs());
                    insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, BigDecimal.ZERO);
                    insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink, currencyInst);
                    insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink, tarCurInst);
                    insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                            new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                    insertPos.execute();
                }
            }
        }
    }
    if (insert != null) {
        final Instance instance = insert.getInstance();
        // create classifications
        final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType();
        final Insert relInsert1 = new Insert(classification1.getClassifyRelationType());
        relInsert1.add(classification1.getRelLinkAttributeName(), instance);
        relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
        relInsert1.execute();

        final Insert classInsert1 = new Insert(classification1);
        classInsert1.add(classification1.getLinkAttributeName(), instance);
        classInsert1.execute();

        final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss.getType();
        final Insert relInsert = new Insert(classification.getClassifyRelationType());
        relInsert.add(classification.getRelLinkAttributeName(), instance);
        relInsert.add(classification.getRelTypeAttributeName(), classification.getId());
        relInsert.execute();

        final Insert classInsert = new Insert(classification);
        classInsert.add(classification.getLinkAttributeName(), instance);
        classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, totalSum);
        classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, totalSum);
        classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, currencyInst);
        classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink, currencyInst);
        classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
        classInsert.execute();
    }
    // clean up
    Context.getThreadContext()
            .removeSessionAttribute(CIFormAccounting.Accounting_GainLoss4SimpleAccountForm.config2period.name);
    return new Return();
}

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

/**
 * Populates the consolidated demand information in CollectionIndexDetails
 *
 * @param collectionDetailsRequest//from  www.  ja v  a2 s.  c  o  m
 * @param collectionIndexDetails
 */
public void getConsolidatedDemandInfo(final CollectionDetailsRequest collectionDetailsRequest,
        final CollectionDetails collectionIndexDetails) {
    Date fromDate;
    Date toDate;
    final CFinancialYear currFinYear = cFinancialYearService.getFinancialYearByDate(new Date());

    /**
     * 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(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), "yyyy-MM-dd");
        toDate = DateUtils.getDate(collectionDetailsRequest.getToDate(), "yyyy-MM-dd");
    } else {
        fromDate = DateUtils.startOfDay(currFinYear.getStartingDate());
        toDate = new Date();
    }
    final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(collectionDetailsRequest);
    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.setCytdDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP));

    collectionIndexDetails.setTotalAssessments(
            collectionIndexElasticSearchService.getTotalAssessmentsCount(collectionDetailsRequest));

    if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
        // performance = (current year tilldate collection * 100)/(proportional demand)
        collectionIndexDetails.setPerformance(
                collectionIndexDetails.getCytdColl().multiply(PropertyTaxConstants.BIGDECIMAL_100)
                        .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));
    // variance = ((currentYearCollection - lastYearCollection)*100)/lastYearCollection
    BigDecimal variation;
    if (collectionIndexDetails.getLytdColl().compareTo(BigDecimal.ZERO) == 0)
        variation = BIGDECIMAL_100;
    else
        variation = collectionIndexDetails.getCytdColl().subtract(collectionIndexDetails.getLytdColl())
                .multiply(BIGDECIMAL_100)
                .divide(collectionIndexDetails.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP);
    collectionIndexDetails.setLyVar(variation);
}

From source file:com.xumpy.timesheets.services.implementations.JobsGraphics.java

public OverviewWorkDetails getOverviewWorkDetails(List<Jobs> jobs) throws ParseException {
    MathContext mc = new MathContext(3, RoundingMode.HALF_UP);

    OverviewWorkDetailsSrvPojo overviewWorkDetails = new OverviewWorkDetailsSrvPojo();

    List<WorkingDay> workingDays = calculateWorkingDates(jobs);

    overviewWorkDetails.setHoursToWorkPerDay(new BigDecimal(8)); // Hardcoded

    BigDecimal hoursPayedPerDay = new BigDecimal(0, mc);
    BigDecimal workedWeekHours = new BigDecimal(0, mc);
    BigDecimal workedWeekendHours = new BigDecimal(0, mc);
    BigDecimal weekDays = new BigDecimal(0, mc);
    BigDecimal weekendDays = new BigDecimal(0, mc);
    BigDecimal workedWeekDays = new BigDecimal(0, mc);
    BigDecimal workedWeekendDays = new BigDecimal(0, mc);
    BigDecimal overtimeHours = new BigDecimal(0, mc);
    BigDecimal overtimeDays = new BigDecimal(0, mc);

    for (WorkingDay workingDay : workingDays) {
        if (CustomDateUtils.isWeekDay(workingDay.getDate())) {
            weekDays = weekDays.add(new BigDecimal(1));
            workedWeekHours = workedWeekHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekDays = workedWeekDays.add(new BigDecimal(1));
        } else {/*from www  .  j  a v a2  s  .co  m*/
            weekendDays = weekendDays.add(new BigDecimal(1));
            workedWeekendHours = workedWeekendHours.add(workingDay.getActualWorkHours(), mc);
            workedWeekendDays = workedWeekendDays.add(new BigDecimal(1));
        }

        overtimeHours = overtimeHours.add(workingDay.getOvertimeHours(), mc);

        for (Jobs jobPerDay : workingDay.getJobs()) {
            if (jobPerDay.getJobsGroup().getCompany() != null) {
                if (hoursPayedPerDay
                        .compareTo(jobPerDay.getJobsGroup().getCompany().getDailyPayedHours()) < 0) {
                    hoursPayedPerDay = jobPerDay.getJobsGroup().getCompany().getDailyPayedHours();
                }
            }
        }

        if (!hoursPayedPerDay.equals(new BigDecimal(0))) {
            overtimeDays = overtimeHours.divide(hoursPayedPerDay, mc);
        } else {
            overtimeDays = workedWeekDays.add(workedWeekendDays);
        }
    }

    overviewWorkDetails.setHoursPayedPerDay(hoursPayedPerDay);

    overviewWorkDetails.setWorkedWeekHours(workedWeekHours);
    overviewWorkDetails.setWorkedWeekendHours(workedWeekendHours);
    overviewWorkDetails.setWeekDays(weekDays);
    overviewWorkDetails.setWeekendDays(weekendDays);

    overviewWorkDetails.setWorkedWeekDays(workedWeekDays);
    overviewWorkDetails.setWorkedWeekendDays(workedWeekendDays);

    overviewWorkDetails.setOvertimeHours(overtimeHours);
    overviewWorkDetails.setOvertimeDays(overtimeDays);

    return overviewWorkDetails;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The integer root.//www.  j av a  2 s .com
 *
 * @param n the positive argument.
 * @param x the non-negative argument.
 * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n).
 */
static public BigDecimal root(final int n, final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("negative argument " + x.toString() + " of root");
    }
    if (n <= 0) {
        throw new ArithmeticException("negative power " + n + " of root");
    }
    if (n == 1) {
        return x;
    }
    /* start the computation from a double precision estimate */
    BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n));
    /* this creates nth with nominal precision of 1 digit
     */
    final BigDecimal nth = new BigDecimal(n);
    /* Specify an internal accuracy within the loop which is
     * slightly larger than what is demanded by eps below.
     */
    final BigDecimal xhighpr = scalePrec(x, 2);
    MathContext mc = new MathContext(2 + x.precision());
    /* Relative accuracy of the result is eps.
     */
    final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue());
    for (;;) {
        /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being
         * smaller than the precision requested. The relative correction is (1-x/s^n)/n,
         */
        BigDecimal c = xhighpr.divide(s.pow(n - 1), mc);
        c = s.subtract(c);
        MathContext locmc = new MathContext(c.precision());
        c = c.divide(nth, locmc);
        s = s.subtract(c);
        if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) {
            break;
        }
    }
    return s.round(new MathContext(err2prec(eps)));
}

From source file:org.sakaiproject.component.gradebook.BaseHibernateManager.java

protected Double calculateEquivalentPointValueForPercent(Double doublePointsPossible,
        Double doublePercentEarned) {
    if (doublePointsPossible == null || doublePercentEarned == null)
        return null;

    BigDecimal pointsPossible = new BigDecimal(doublePointsPossible.toString());
    BigDecimal percentEarned = new BigDecimal(doublePercentEarned.toString());
    BigDecimal equivPoints = pointsPossible
            .multiply(percentEarned.divide(new BigDecimal("100"), GradebookService.MATH_CONTEXT));
    return Double.valueOf(equivPoints.doubleValue());
}

From source file:org.openconcerto.erp.graph.GraphFamilleArticlePanel.java

protected BigDecimal updateDataset(List<String> labels, List<Number> values) {

    final SQLTable tableVFElement = Configuration.getInstance().getDirectory()
            .getElement("SAISIE_VENTE_FACTURE_ELEMENT").getTable();
    final SQLTable tableVF = tableVFElement.getTable("SAISIE_VENTE_FACTURE");
    final SQLTable tableArticle = tableVFElement.getTable("ARTICLE");

    final SQLSelect sel = new SQLSelect();
    final String field = "ID_FAMILLE_ARTICLE";

    sel.addSelect(tableArticle.getField(field));

    sel.addSelect(tableVFElement.getField("T_PA_HT"), "SUM");
    sel.addSelect(tableVFElement.getField("T_PV_HT"), "SUM");
    sel.addSelect(tableVFElement.getField("QTE"), "SUM");

    Where w = new Where(tableVF.getKey(), "=", tableVFElement.getField("ID_SAISIE_VENTE_FACTURE"));
    w = w.and(new Where(tableVF.getField("DATE"), this.d1, this.d2));
    w = w.and(new Where(tableArticle.getKey(), "=", tableVFElement.getField("ID_ARTICLE")));
    sel.setWhere(w);/*w ww  . j  av  a2 s.  c  o  m*/

    final List<Object[]> rowsArticle = (List<Object[]>) Configuration.getInstance().getBase().getDataSource()
            .execute(sel.asString() + " GROUP BY \"ARTICLE\".\"" + field + "\"", new ArrayListHandler());

    Collections.sort(rowsArticle, new Comparator<Object[]>() {
        @Override
        public int compare(Object[] o1, Object[] o2) {

            BigDecimal pa1 = (BigDecimal) o1[1];
            BigDecimal pv1 = (BigDecimal) o1[2];
            BigDecimal qte1 = new BigDecimal(o1[3].toString());

            BigDecimal pa2 = (BigDecimal) o2[1];
            BigDecimal pv2 = (BigDecimal) o2[2];
            BigDecimal qte2 = new BigDecimal(o2[3].toString());

            BigDecimal marge1 = pv1.subtract(pa1).multiply(qte1, DecimalUtils.HIGH_PRECISION);
            BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, DecimalUtils.HIGH_PRECISION);
            return pv1.compareTo(pv2);
        }
    });

    SQLTable tableFamille = tableVFElement.getTable("FAMILLE_ARTICLE");

    BigDecimal total = BigDecimal.ZERO;
    for (int i = 0; i < rowsArticle.size(); i++) {
        Object[] o = rowsArticle.get(i);

        BigDecimal pv2 = (BigDecimal) o[2];
        total = total.add(pv2);
    }
    if (total.signum() > 0) {

        for (int i = 0; i < 12 && i < rowsArticle.size(); i++) {
            Object[] o = rowsArticle.get(i);
            BigDecimal pa2 = (BigDecimal) o[1];
            BigDecimal pv2 = (BigDecimal) o[2];
            BigDecimal qte2 = new BigDecimal(o[3].toString());
            BigDecimal marge2 = pv2.subtract(pa2).multiply(qte2, DecimalUtils.HIGH_PRECISION);

            String s = "Indfini";
            if (o[0] != null) {
                int id = ((Number) o[0]).intValue();
                s = tableFamille.getRow(id).getString("NOM");
            }
            values.add(pv2);
            labels.add(s + "(" + decFormat.format(pv2.setScale(2, RoundingMode.HALF_UP).doubleValue())
                    + " soit " + pv2.divide(total, DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2,
                            RoundingMode.HALF_UP)
                    + "%)");
        }
    }
    return total;
}

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

/**
 * Returns Top Ten with ULB wise grouping and total amount aggregation
 *
 * @param collectionDetailsRequest//from  www.j  a v a2 s . co m
 * @param indexName
 * @param order
 * @param orderingAggregationName
 * @return
 */
public List<TaxPayerDetails> returnUlbWiseAggregationResults(
        final CollectionDetailsRequest collectionDetailsRequest, final String indexName, final Boolean order,
        final String orderingAggregationName, final int size, final boolean isBillCollectorWise,
        CFinancialYear currFinYear) {
    BigDecimal proportionalArrearDmd;
    BigDecimal proportionalCurrDmd;
    BigDecimal variation;
    Sum totalDemandAggregation;
    Sum totalCollectionAggregation;
    Sum arrearDmd;
    Sum currentDmd;
    Sum arrearInterestDmd;
    Sum currentInterestDmd;
    Sum arrearCollAmt;
    Sum currentCollAmt;
    Sum arrearIntColl;
    Sum currentIntColl;
    final List<TaxPayerDetails> taxPayers = new ArrayList<>();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    final BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest)
            .filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
            .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));

    // orderingAggregationName is the aggregation name by which we have to
    // order the results
    // IN this case can be one of "totaldemand" or "total_collection" or
    // "avg_achievement"
    String groupingField;
    if (StringUtils.isNotBlank(collectionDetailsRequest.getUlbCode()) || StringUtils
            .isNotBlank(collectionDetailsRequest.getType())
            && (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_BILLCOLLECTORWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEINSPECTORWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEOFFICERWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())))
        groupingField = REVENUE_WARD;
    else
        groupingField = CITY_NAME;

    AggregationBuilder aggregation;
    SearchQuery searchQueryColl;
    // Apply the ordering and max results size only if the type is not
    // billcollector
    if (!isBillCollectorWise) {
        aggregation = prepareAggregationForTaxPayers(size, groupingField)
                .order(Terms.Order.aggregation(orderingAggregationName, order));
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .addAggregation(aggregation).build();
    } else {
        aggregation = prepareAggregationForTaxPayers(250, groupingField);
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build();
    }

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate());
    final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1);
    final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1);

    // Fetch ward wise Bill Collector details for ward based grouping
    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()))
        wardWiseBillCollectors = collectionIndexElasticSearchService
                .getWardWiseBillCollectors(collectionDetailsRequest);

    TaxPayerDetails taxDetail;
    final StringTerms totalAmountAggr = collAggr.get(BY_AGGREGATION_FIELD);
    BigDecimal lastYearCollection;
    for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) {
        taxDetail = new TaxPayerDetails();
        taxDetail.setRegionName(collectionDetailsRequest.getRegionName());
        taxDetail.setDistrictName(collectionDetailsRequest.getDistrictName());
        taxDetail.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        final String fieldName = String.valueOf(entry.getKey());
        // If the grouping is based on ward, set the Bill Collector name and number
        if (groupingField.equals(REVENUE_WARD)) {
            taxDetail.setWardName(fieldName);
            if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    && !wardWiseBillCollectors.isEmpty()) {
                taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollector());
                taxDetail.setBillCollMobNo(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorMobileNo());
                taxDetail.setBillCollectorCode(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorCode());
            }
        } else
            taxDetail.setUlbName(fieldName);

        // Proportional Demand = (totalDemand/12)*noOfmonths
        final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
        totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND);
        totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION);
        arrearDmd = entry.getAggregations().get(ARREAR_DMD_STR);
        currentDmd = entry.getAggregations().get(CURR_DMD);
        arrearInterestDmd = entry.getAggregations().get(ARREAR_INTEREST_DMD);
        currentInterestDmd = entry.getAggregations().get(CURR_INTEREST_DMD);
        arrearCollAmt = entry.getAggregations().get(ARREAR_COLLECTION);
        currentCollAmt = entry.getAggregations().get(ANNUAL_COLLECTION);
        arrearIntColl = entry.getAggregations().get(ARREAR_INTEREST_COLLECTION);
        currentIntColl = entry.getAggregations().get(CURRENT_INTEREST_COLLECTION);

        final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP);
        final BigDecimal proportionalDemand = totalDemandValue
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setTotalDmd(totalDemandValue);
        taxDetail.setCytdColl(totalCollections);
        taxDetail.setCytdDmd(proportionalDemand);
        if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
            taxDetail.setAchievement(totalCollections.multiply(BIGDECIMAL_100).divide(proportionalDemand, 1,
                    BigDecimal.ROUND_HALF_UP));
        taxDetail.setCytdBalDmd(proportionalDemand.subtract(totalCollections));
        if (StringUtils.isNotBlank(taxDetail.getUlbName()))
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, fieldName, null, "totalAmount");
        else
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, null, fieldName, "totalAmount");
        taxDetail.setLytdColl(lastYearCollection);
        taxDetail.setArrearColl(
                BigDecimal.valueOf(arrearCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentColl(
                BigDecimal.valueOf(currentCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setInterestColl(
                BigDecimal.valueOf(arrearIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).add(
                        BigDecimal.valueOf(currentIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        taxDetail.setArrearDemand(
                BigDecimal.valueOf(arrearDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentDemand(
                BigDecimal.valueOf(currentDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setArrearInterestDemand(
                BigDecimal.valueOf(arrearInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentInterestDemand(
                BigDecimal.valueOf(currentInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        proportionalArrearDmd = taxDetail.getArrearDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        proportionalCurrDmd = taxDetail.getCurrentDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setProportionalArrearDemand(proportionalArrearDmd);
        taxDetail.setProportionalCurrentDemand(proportionalCurrDmd);

        // variance = ((currentYearCollection -
        // lastYearCollection)*100)/lastYearCollection

        if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0)
            variation = BIGDECIMAL_100;
        else
            variation = totalCollections.subtract(lastYearCollection).multiply(BIGDECIMAL_100)
                    .divide(lastYearCollection, 1, BigDecimal.ROUND_HALF_UP);
        taxDetail.setLyVar(variation);
        taxPayers.add(taxDetail);
    }
    // If for Bill Collector, then fetch details for all wards, else limit
    // the results size
    if (isBillCollectorWise)
        return taxPayers;
    else
        return returnTopResults(taxPayers, size, order);
}

From source file:org.sakaiproject.component.gradebook.BaseHibernateManager.java

/**
 * /* w ww .  j a v  a 2  s .c  o m*/
 * @param doublePointsPossible
 * @param doublePointsEarned
 * @return the % equivalent for the given points possible and points earned
 */
protected Double calculateEquivalentPercent(Double doublePointsPossible, Double doublePointsEarned) {

    if (doublePointsEarned == null || doublePointsPossible == null)
        return null;

    // scale to handle points stored as repeating decimals
    BigDecimal pointsEarned = new BigDecimal(doublePointsEarned.toString());
    BigDecimal pointsPossible = new BigDecimal(doublePointsPossible.toString());

    BigDecimal equivPercent = pointsEarned.divide(pointsPossible, GradebookService.MATH_CONTEXT)
            .multiply(new BigDecimal("100"));
    return Double.valueOf(equivPercent.doubleValue());

}