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.openlmis.rnr.domain.RnrLineItem.java

private Integer calculateNormalizedConsumption(BigDecimal stockOutDays, BigDecimal quantityDispensed,
        BigDecimal newPatientCount, BigDecimal dosesPerMonth, BigDecimal dosesPerDispensingUnit,
        Integer reportingDays, ProgramRnrTemplate template) {

    BigDecimal newPatientFactor;//from ww w. ja  v  a2s  . c o  m
    if (template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption() != null
            && template.getRnrColumnsMap().get("newPatientCount").getConfiguredOption().getName()
                    .equals("newPatientCount")) {
        newPatientFactor = newPatientCount
                .multiply(dosesPerMonth.divide(dosesPerDispensingUnit, MATH_CONTEXT).setScale(0, HALF_UP));
    } else {
        newPatientFactor = newPatientCount;
    }

    if (reportingDays == null || stockOutDays.compareTo(new BigDecimal(reportingDays)) >= 0) {
        return quantityDispensed.add(newPatientFactor).setScale(0, HALF_UP).intValue();
    }

    BigDecimal stockOutFactor = quantityDispensed.multiply(
            NUMBER_OF_DAYS.divide((new BigDecimal(reportingDays).subtract(stockOutDays)), MATH_CONTEXT));

    return stockOutFactor.add(newPatientFactor).setScale(0, HALF_UP).intValue();
}

From source file:com.gst.portfolio.savings.domain.SavingsAccountCharge.java

private BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) {

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, MoneyHelper.getRoundingMode());
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }/*from  w  w  w  .  j a v a2  s  . c  o m*/

    return percentageOf;
}

From source file:org.egov.ptis.domain.service.transfer.PropertyTransferService.java

/**
 * API to calculate mutation fee/*from w w w.j a  v a  2 s  .  c  o m*/
 *
 * @param partyValue
 * @param departmentValue
 * @return MutationFee
 */
public BigDecimal calculateMutationFee(final BigDecimal partyValue, final BigDecimal departmentValue) {
    BigDecimal mutationFee = BigDecimal.ZERO;
    BigDecimal documentValue = partyValue.compareTo(departmentValue) > 0 ? partyValue : departmentValue;

    if (documentValue.compareTo(BigDecimal.ZERO) > 0) {
        List<MutationFeeDetails> mutationFeeDetailsList = mutationFeeRepository.getMutationFee(documentValue);
        if (!mutationFeeDetailsList.isEmpty()) {
            MutationFeeDetails mutationFeeDetails = mutationFeeDetailsList.get(0);
            if (mutationFeeDetails != null) {
                if (mutationFeeDetails.getFlatAmount() != null
                        && mutationFeeDetails.getFlatAmount().compareTo(BigDecimal.ZERO) > 0)
                    if ("N".equalsIgnoreCase(mutationFeeDetails.getIsRecursive().toString()))
                        mutationFee = mutationFeeDetails.getFlatAmount();
                    else {
                        BigDecimal excessDocValue = documentValue.subtract(mutationFeeDetails.getLowLimit())
                                .add(BigDecimal.ONE);
                        BigDecimal multiplicationFactor = excessDocValue
                                .divide(mutationFeeDetails.getRecursiveFactor(), BigDecimal.ROUND_CEILING);
                        mutationFee = mutationFeeDetails.getFlatAmount()
                                .add(multiplicationFactor.multiply(mutationFeeDetails.getRecursiveAmount()));
                    }
                if (mutationFeeDetails.getPercentage() != null
                        && mutationFeeDetails.getPercentage().compareTo(BigDecimal.ZERO) > 0
                        && mutationFeeDetails.getIsRecursive().toString().equalsIgnoreCase("N"))
                    mutationFee = documentValue.multiply(mutationFeeDetails.getPercentage())
                            .divide(PropertyTaxConstants.BIGDECIMAL_100);
            }
        }
    }
    return mutationFee.setScale(0, BigDecimal.ROUND_HALF_UP);
}

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

/**
 * Returns Top Ten with ULB wise grouping and total amount aggregation
 *
 * @param waterChargedashBoardRequest//from w ww  . j  a va2s.c  o  m
 * @param indexName
 * @param order
 * @param orderingAggregationName
 * @return
 */
public List<WaterTaxPayerDetails> returnUlbWiseAggregationResults(
        final WaterChargeDashBoardRequest waterChargedashBoardRequest, final String indexName,
        final Boolean order, final String orderingAggregationName, final int size,
        final boolean isBillCollectorWise) {
    final List<WaterTaxPayerDetails> taxPayers = new ArrayList<>();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    final BoolQueryBuilder boolQuery = waterChargeCollDocService.prepareWhereClause(waterChargedashBoardRequest,
            null);
    CFinancialYear currFinYear = cFinancialYearService.getCurrentFinancialYear();

    // 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(waterChargedashBoardRequest.getUlbCode()) || StringUtils
            .isNotBlank(waterChargedashBoardRequest.getType())
            && (waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE)
                    || waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_BILLCOLLECTORWISE)))
        groupingField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD;
    else
        groupingField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD;

    Long startTime = System.currentTimeMillis();
    @SuppressWarnings("rawtypes")
    AggregationBuilder aggregation;
    SearchQuery searchQueryColl;
    // Apply the ordering and max results size only if the type is not
    // billcollector
    if (!isBillCollectorWise) {
        aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(size)
                .order(Terms.Order.aggregation(orderingAggregationName, order))
                .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND))
                .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection"));
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .addAggregation(aggregation).build();
    } else {
        aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(250)
                .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND))
                .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection"));
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build();
    }

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());
    // Fetch ward wise Bill Collector details for ward based grouping
    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType()))
        wardWiseBillCollectors = waterChargeCollDocService
                .getWardWiseBillCollectors(waterChargedashBoardRequest);
    Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by ulbWiseAggregations is (millisecs) : " + timeTaken);
    WaterTaxPayerDetails taxDetail;
    startTime = System.currentTimeMillis();
    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);
    final StringTerms totalAmountAggr = collAggr.get(AGGREGATION_FIELD);
    for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) {
        taxDetail = new WaterTaxPayerDetails();
        taxDetail.setRegionName(waterChargedashBoardRequest.getRegionName());
        taxDetail.setDistrictName(waterChargedashBoardRequest.getDistrictName());
        taxDetail.setUlbGrade(waterChargedashBoardRequest.getUlbGrade());
        final String fieldName = String.valueOf(entry.getKey());
        if (groupingField.equals(WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD)) {
            taxDetail.setWardName(fieldName);
            if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType())
                    && !wardWiseBillCollectors.isEmpty())
                taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollector());
        } else
            taxDetail.setUlbName(fieldName);
        // Proportional Demand = (totalDemand/12)*noOfmonths
        final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
        final Sum totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND);
        final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_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.setCurrentYearTillDateColl(totalCollections);
        taxDetail.setCurrentYearTillDateDmd(proportionalDemand);
        taxDetail.setAchievement(totalCollections.multiply(WaterTaxConstants.BIGDECIMAL_100)
                .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentYearTillDateBalDmd(proportionalDemand.subtract(totalCollections));
        final BigDecimal lastYearCollection = waterChargeCollDocService.getCollectionBetweenDates(
                waterChargedashBoardRequest, lastYearFromDate, lastYearToDate, fieldName);
        // variance = ((lastYearCollection/currentYearCollection )*100)
        BigDecimal variation = BigDecimal.ZERO;
        taxDetail.setLastYearTillDateColl(lastYearCollection);
        if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0)
            variation = WaterTaxConstants.BIGDECIMAL_100;
        else if (totalCollections.compareTo(BigDecimal.ZERO) > 0)
            variation = taxDetail.getCurrentYearTillDateColl().subtract(taxDetail.getLastYearTillDateColl())
                    .multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(taxDetail.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
        /*
         * variation
         * =taxDetail.getLastYearTillDateColl().multiply(WaterTaxConstants.
         * BIGDECIMAL_100) .divide(totalCollections, 1,
         * BigDecimal.ROUND_HALF_UP);
         */
        taxDetail.setLastYearVar(variation);
        taxPayers.add(taxDetail);
    }
    timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is (millisecs) : "
                + timeTaken);
    return returnTopResults(taxPayers, size, order);
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL <code>/</code> operator applied to BigDecimal values. */
public static BigDecimal divide(BigDecimal b0, BigDecimal b1) {
    return (b0 == null || b1 == null) ? null : b0.divide(b1, MathContext.DECIMAL64);
}

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

/**
 * Convert an absolute error to a precision.
 *
 * @param x    The value of the variable
 * @param xerr The absolute error in the variable
 * @return The number of valid digits in x.
 * The value is rounded down, and on the pessimistic side for that reason.
 */// w w  w . j a  va  2  s  .  co m
static public int err2prec(BigDecimal x, BigDecimal xerr) {
    return err2prec(xerr.divide(x, MathContext.DECIMAL64).doubleValue());

}

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

/**
 * Populates the consolidated demand information in CollectionIndexDetails
 *
 * @param waterChargedashBoardRequest/*from ww w  . ja  v  a 2s  .  c  o 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:services.kpi.PortfolioEntryProgressKpi.java

@Override
public BigDecimal computeMain(IPreferenceManagerPlugin preferenceManagerPlugin, IScriptService scriptService,
        Kpi kpi, Long objectId) {
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(objectId);

    BigDecimal numerator = BigDecimal.ZERO;
    BigDecimal denominator = BigDecimal.ZERO;
    BigDecimal value = new BigDecimal(100);

    for (PortfolioEntryPlanningPackage planningPackage : portfolioEntry.planningPackages) {

        BigDecimal days = PortfolioEntryResourcePlanDAO
                .getPEPlanAllocatedActorAsDaysByPlanningPackage(planningPackage)
                .add(PortfolioEntryResourcePlanDAO
                        .getPEResourcePlanAllocatedOrgUnitAsDaysByPlanningPackage(planningPackage))
                .add(PortfolioEntryResourcePlanDAO
                        .getPEResourcePlanAllocatedCompetencyAsDaysByPlanningPackage(planningPackage));

        denominator = denominator.add(days);

        switch (planningPackage.status) {
        case CLOSED:
            numerator = numerator.add(days);
            break;
        case ON_GOING:
            numerator = numerator.add(days.multiply(getOnGoingRate(preferenceManagerPlugin)));
            break;
        default:/*  www.  jav a2  s  .  c o  m*/
            break;
        }

    }

    if (!denominator.equals(BigDecimal.ZERO)) {
        value = numerator.divide(denominator, RoundingMode.HALF_UP).multiply(value);
    }

    return value;
}

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

/**
 * Divide and round./*www.j  a va  2  s. c om*/
 *
 * @param x The numerator
 * @param n The denominator
 * @return the divided x/n
 */
static public BigDecimal divideRound(final BigDecimal x, final int n) {
    /* The estimation of the relative error in the result is |err(x)/x|
     */
    MathContext mc = new MathContext(x.precision());

    return x.divide(new BigDecimal(n), mc);

}

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

/**
 * Divide and round.//  w  w  w .  j av a2 s.  c om
 *
 * @param x The numerator
 * @param n The denominator
 * @return the divided x/n
 */
static public BigDecimal divideRound(final BigDecimal x, final BigInteger n) {
    /* The estimation of the relative error in the result is |err(x)/x|
     */
    MathContext mc = new MathContext(x.precision());

    return x.divide(new BigDecimal(n), mc);

}