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:dk.clanie.money.Money.java

/**
 * Divide evenly into parts.//  w  ww .  j  a v a2  s . co m
 * 
 * Divides an amount into parts of approximately the same size while
 * ensuring that the sum of all the parts equals the whole.
 * <p>
 * Parts of unequal size will be distributed evenly in the returned array.
 * <p>
 * For example, if asked to divede 20 into 6 parts the result will be {3.33,
 * 3.34, 3.33, 3.33, 3.34, 3.33}
 * 
 * @param parts -
 *            number of parts
 * @return Money[] with the parts
 */
public Money[] divideEvenlyIntoParts(int parts) {
    Money[] res = new Money[parts];
    final BigDecimal bdParts = new BigDecimal(parts);
    final MathContext mc = MathContext.DECIMAL128;
    BigDecimal sumOfPreviousParts = BigDecimal.ZERO;
    for (int i = 0; i < parts; i++) {
        Money part = new Money();
        BigDecimal sumOfParts = amount.multiply(new BigDecimal(i + 1));
        sumOfParts = sumOfParts.divide(bdParts, mc);
        sumOfParts = sumOfParts.setScale(amount.scale(), mc.getRoundingMode());
        part.amount = sumOfParts.subtract(sumOfPreviousParts);
        sumOfPreviousParts = sumOfParts;
        part.currency = currency;
        res[i] = part;
    }
    return res;
}

From source file:org.yccheok.jstock.analysis.ArithmeticOperator.java

private Double division() {
    Object object0 = inputs[0].getValue();
    Object object1 = inputs[1].getValue();

    try {/*from  w  ww .  j  a v  a  2  s  .c om*/
        BigDecimal d0 = new BigDecimal(object0.toString());
        BigDecimal d1 = new BigDecimal(object1.toString());

        final double d1Value = d1.doubleValue();
        if (d1Value != 0.0) {
            BigDecimal result = d0.divide(d1, MathContext.DECIMAL64);
            return result.doubleValue();
        }
    } catch (NumberFormatException exp) {
        log.error(null, exp);
    }

    return null;
}

From source file:services.kpi.PortfolioEntryProgressKpi.java

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

    BigDecimal value = BigDecimal.ZERO;

    for (PortfolioEntryPlanningPackage planningPackage : portfolioEntry.planningPackages) {
        value = value.add(TimesheetDao.getTimesheetLogAsTotalHoursByPEPlanningPackage(planningPackage));
    }/*  w  w  w  .j a  v a  2s .  c  om*/

    return value.divide(TimesheetDao.getTimesheetReportHoursPerDay(preferenceManagerPlugin),
            RoundingMode.HALF_UP);
}

From source file:org.onebusaway.admin.util.VehicleStatusBuilder.java

private String getLastUpdate(String timeReported) {
    String lastUpdate;//from   w  w  w  .j  a v  a 2 s. co m
    BigDecimal difference = getTimeDifference(timeReported);
    if (difference.abs().compareTo(new BigDecimal(86400)) > 0) {
        //Calculate the difference in days
        BigDecimal days = difference.divide(new BigDecimal(86400), BigDecimal.ROUND_HALF_UP);
        lastUpdate = days.toPlainString() + " days";
    } else {
        if (difference.abs().compareTo(new BigDecimal(3600)) > 0) {
            //Calculate the difference in hours
            BigDecimal hours = difference.divide(new BigDecimal(3600), BigDecimal.ROUND_HALF_UP);
            lastUpdate = hours.toPlainString() + " hours";
        } else {
            if (difference.abs().compareTo(new BigDecimal(60)) > 0) {
                //Calculate the difference in minutes
                BigDecimal minutes = difference.divide(new BigDecimal(60), BigDecimal.ROUND_UP);
                lastUpdate = minutes.toPlainString() + " mins";
            } else {
                lastUpdate = difference + " sec";
            }
        }
    }
    return lastUpdate;
}

From source file:com.sun.faces.el.impl.DivideOperator.java

/**
 * Applies the operator to the given value
 *//*from www.ja  va  2  s . c  o m*/
public Object apply(Object pLeft, Object pRight) throws ElException {
    if (pLeft == null && pRight == null) {
        if (log.isWarnEnabled()) {
            log.warn(MessageUtil.getMessageWithArgs(Constants.ARITH_OP_NULL, getOperatorSymbol()));
        }
        return PrimitiveObjects.getInteger(0);
    }

    if (Coercions.isBigDecimal(pLeft) || Coercions.isBigInteger(pLeft) || Coercions.isBigDecimal(pRight)
            || Coercions.isBigInteger(pRight)) {

        BigDecimal left = (BigDecimal) Coercions.coerceToPrimitiveNumber(pLeft, BigDecimal.class);
        BigDecimal right = (BigDecimal) Coercions.coerceToPrimitiveNumber(pRight, BigDecimal.class);

        try {
            return left.divide(right, BigDecimal.ROUND_HALF_UP);
        } catch (Exception exc) {
            if (log.isErrorEnabled()) {
                String message = MessageUtil.getMessageWithArgs(Constants.ARITH_ERROR, getOperatorSymbol(),
                        "" + left, "" + right);
                log.error(message);
                throw new ElException(message);
            }
            return PrimitiveObjects.getInteger(0);
        }
    } else {

        double left = Coercions.coerceToPrimitiveNumber(pLeft, Double.class).doubleValue();
        double right = Coercions.coerceToPrimitiveNumber(pRight, Double.class).doubleValue();

        try {
            return PrimitiveObjects.getDouble(left / right);
        } catch (Exception exc) {
            if (log.isErrorEnabled()) {
                String message = MessageUtil.getMessageWithArgs(Constants.ARITH_ERROR, getOperatorSymbol(),
                        "" + left, "" + right);
                log.error(message);
                throw new ElException(message);
            }
            return PrimitiveObjects.getInteger(0);
        }
    }
}

From source file:org.sakaiproject.tool.gradebook.CourseGradeRecord.java

public void initNonpersistentFields(double totalPointsPossible, double totalPointsEarned) {
    Double percentageEarned;//from  w w  w .  j  a v  a 2s  .  c  om
    this.totalPointsPossible = totalPointsPossible;
    calculatedPointsEarned = totalPointsEarned;
    BigDecimal bdTotalPointsPossible = new BigDecimal(totalPointsPossible);
    BigDecimal bdTotalPointsEarned = new BigDecimal(totalPointsEarned);
    if (totalPointsPossible == 0.0) {
        percentageEarned = null;
    } else {
        percentageEarned = Double
                .valueOf(bdTotalPointsEarned.divide(bdTotalPointsPossible, GradebookService.MATH_CONTEXT)
                        .multiply(new BigDecimal("100")).doubleValue());
    }
    autoCalculatedGrade = percentageEarned;
}

From source file:org.sakaiproject.tool.gradebook.CourseGradeRecord.java

public void initNonpersistentFields(double totalPointsPossible, double totalPointsEarned,
        double literalTotalPointsEarned) {
    Double percentageEarned;/*  w  w w .  jav a2s  .co m*/
    //calculatedPointsEarned = totalPointsEarned;
    calculatedPointsEarned = literalTotalPointsEarned;
    this.totalPointsPossible = totalPointsPossible;
    BigDecimal bdTotalPointsPossible = new BigDecimal(totalPointsPossible);
    BigDecimal bdTotalPointsEarned = new BigDecimal(totalPointsEarned);

    if (totalPointsPossible <= 0.0) {
        percentageEarned = null;
    } else {
        percentageEarned = Double
                .valueOf(bdTotalPointsEarned.divide(bdTotalPointsPossible, GradebookService.MATH_CONTEXT)
                        .multiply(new BigDecimal("100")).doubleValue());
    }
    autoCalculatedGrade = percentageEarned;
}

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

public void setPercentage(BigDecimal percentage) {
    if (percentage != null) {
        BigDecimal proportion = percentage.divide(new BigDecimal(100), BigDecimal.ROUND_DOWN);
        hoursGroup.setPercentage(proportion);
    } else {/*from   w w w . java 2  s.c o m*/
        hoursGroup.setPercentage(new BigDecimal(0).setScale(2));
    }

}

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

private BigDecimal getPercentageInOrderLineGroup(Integer workHours) {
    BigDecimal workingHours = new BigDecimal(hoursGroup.getWorkingHours()).setScale(2);
    BigDecimal total = new BigDecimal(workHours).setScale(2);

    return total.equals(new BigDecimal(0).setScale(2)) ? new BigDecimal(0).setScale(2)
            : workingHours.divide(total, BigDecimal.ROUND_DOWN).scaleByPowerOfTen(2);
}

From source file:org.libreplan.business.orders.daos.OrderElementDAO.java

private BigDecimal average(BigDecimal divisor, BigDecimal sum) {
    BigDecimal average = new BigDecimal(0);
    if (sum.compareTo(new BigDecimal(0)) > 0) {
        average = sum.divide(divisor, new MathContext(2, RoundingMode.HALF_UP));
    }//  w ww.j  a va  2s.  c  om
    return average;
}