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) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose preferred scale is (this.scale() - divisor.scale()) ; if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.

Usage

From source file:nl.strohalm.cyclos.controls.reports.statistics.graphs.StatisticalDataProducer.java

/**
 * Cewolf needs this method for generation of tooltips when you hoover the mouse over a Pie graph section. If the settings are available, use
 * them, if not, then unformatted numbers will be shown. As tooltips are not essential, and as generation of them should never allow the rendering
 * of graphs to fail due to exceptions, all is inside a try catch block.
 * //from   ww  w .j  av a 2  s .com
 * @param dataset a <code>PieDataset</code>
 * @param key for identifying the section.
 * @param pieIndex in case of multiple Pie charts. Not used in cyclos.
 */
@Override
@SuppressWarnings("rawtypes")
public String generateToolTip(final PieDataset dataset, final Comparable key, final int pieIndex) {
    try {
        final Number number = dataset.getValue(key);
        try {
            final byte precision = (number instanceof StatisticalNumber)
                    ? ((StatisticalNumber) number).getPrecision()
                    : 0;
            if (settings != null) {
                final BigDecimal value = (new BigDecimal(1000).pow(scaleFactor))
                        .multiply(new BigDecimal(number.floatValue()));
                final int percentage = (int) Math
                        .round(value.divide(new BigDecimal(getTotalForPie())).doubleValue() * 100);
                final String result = settings.getNumberConverterForPrecision(precision).toString(value) + " (="
                        + percentage + "%)";
                return result;
            }
        } catch (final Exception e) {
            // if anything goes wrong, do nothing but continue with String.valueOf
        }
        final String result = String.valueOf(number.doubleValue());
        final int percentage = (int) Math.round(100 * (number.doubleValue() / getTotalForPie()));
        return result + " (=" + percentage + "%)";
    } catch (final Exception e) {
        // if all failed, just return no tooltips
        return "";
    }
}

From source file:org.sonar.plugins.qualityprofileprogression.batch.ProfileProgressionDecorator.java

protected int getProjectsViolationPercentage(DecoratorContext context) {
    List<Violation> violations = context.getViolations();
    logger.debug("Found {} violations.", violations.size());

    List<ActiveRule> rules = profile.getActiveRules();
    logger.debug("Found {} rules.", rules.size());

    // get base measures
    BigDecimal numberOfViolations = new BigDecimal(violations.size());
    BigDecimal numberOfRules = new BigDecimal(rules.size());

    // get violation ratio
    BigDecimal projectViolationDecimal = null;
    if (numberOfRules.equals(new BigDecimal(0)))
    // no rules so 0% violations
    {//from ww  w.j a va  2  s. c  om
        projectViolationDecimal = new BigDecimal(0);
    } else {
        projectViolationDecimal = numberOfViolations.divide(numberOfRules);
    }

    // convert to percentage
    int projectViolationPercentage = projectViolationDecimal.multiply(new BigDecimal(100)).intValue();

    logger.debug("Project's % violations: {}", projectViolationPercentage);

    return projectViolationPercentage;
}

From source file:com.abiquo.api.services.cloud.VirtualApplianceService.java

@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
private void getAdditionalStorageCost(final Map<VirtualMachineCost, BigDecimal> virtualMachinesCost,
        final Collection<RasdManagement> resources, final PricingTemplate pricing) {

    for (final RasdManagement resource : resources) {
        if (resource instanceof VolumeManagement) {
            final VolumeManagement volman = (VolumeManagement) resource;
            // accum += volman.getSizeInMB();
            Tier tier = pricingRep.findTierById(volman.getStoragePool().getTier().getId());
            PricingTier pricingTier = pricingRep.findPricingTier(tier, pricing);
            if (pricingTier != null) {
                BigDecimal volum = new BigDecimal(volman.getSizeInMB());
                BigDecimal toGB = new BigDecimal(1024);
                virtualMachinesCost.put(VirtualMachineCost.ADDITIONAL_VOLUME,
                        virtualMachinesCost.get(VirtualMachineCost.ADDITIONAL_VOLUME)
                                .add(pricingTier.getPrice().multiply(volum.divide(toGB))));// multiplicar
                // por
                // _MB
            }//  ww  w .  j ava2 s  .  com
        }
    }
}

From source file:com.sentaroh.android.SMBExplorer.FileIo.java

private static String calTransferRate(long tb, long tt) {
    String tfs = null;/*from   w  w  w  .  ja v a2s .c om*/
    BigDecimal bd_tr;
    if (tb > (1024)) {//KB
        BigDecimal dfs1 = new BigDecimal(tb * 1.000);
        BigDecimal dfs2 = new BigDecimal(1024 * 1.000);
        BigDecimal dfs3 = new BigDecimal("0.000000");
        dfs3 = dfs1.divide(dfs2);
        BigDecimal dft1 = new BigDecimal(tt * 1.000);
        BigDecimal dft2 = new BigDecimal(1000.000);
        BigDecimal dft3 = new BigDecimal("0.000000");
        dft3 = dft1.divide(dft2);
        bd_tr = dfs3.divide(dft3, 2, BigDecimal.ROUND_HALF_UP);
        tfs = bd_tr + "KBytes/sec";
    } else {
        BigDecimal dfs1 = new BigDecimal(tb * 1.000);
        BigDecimal dfs2 = new BigDecimal(1024 * 1.000);
        BigDecimal dfs3 = new BigDecimal("0.000000");
        dfs3 = dfs1.divide(dfs2);
        BigDecimal dft1 = new BigDecimal(tt * 1.000);
        BigDecimal dft2 = new BigDecimal(1000.000);
        BigDecimal dft3 = new BigDecimal("0.000000");
        dft3 = dft1.divide(dft2);
        bd_tr = dfs3.divide(dft3, 2, BigDecimal.ROUND_HALF_UP);
        tfs = bd_tr + "Bytes/sec";
    }

    return tfs;
}

From source file:org.openhab.binding.sensebox.internal.handler.SenseBoxHandler.java

private State decimalFromSensor(SenseBoxSensor data) {
    State result = UnDefType.UNDEF;

    if (data != null) {
        if (data.getLastMeasurement() != null) {
            if (StringUtils.isNotEmpty(data.getLastMeasurement().getValue())) {
                logger.debug("About to determine quantity for {} / {}", data.getLastMeasurement().getValue(),
                        data.getUnit());
                BigDecimal bd = new BigDecimal(data.getLastMeasurement().getValue());

                switch (data.getUnit()) {
                case "%":
                    result = new QuantityType<>(bd, SmartHomeUnits.ONE);
                    break;
                case "C":
                    result = new QuantityType<>(bd, SIUnits.CELSIUS);
                    break;
                case "Pa":
                    result = new QuantityType<>(bd, SIUnits.PASCAL);
                    break;
                case "hPa":
                    if (BigDecimal.valueOf(10000l).compareTo(bd) < 0) {
                        // Some stations report measurements in Pascal, but send 'hPa' as units...
                        bd = bd.divide(ONEHUNDRED);
                    }/*from w  w  w .j  a  va2s.com*/
                    result = new QuantityType<>(bd, HECTO(SIUnits.PASCAL));
                    break;
                case "lx":
                    result = new QuantityType<>(bd, SmartHomeUnits.LUX);
                    break;
                case "\u00b5g/m":
                    result = new QuantityType<>(bd, SmartHomeUnits.MICROGRAM_PER_CUBICMETRE);
                    break;
                case "\u00b5W/cm":
                    result = new QuantityType<>(bd, SmartHomeUnits.MICROWATT_PER_SQUARE_CENTIMETRE);
                    break;
                default:
                    // The data provider might have configured some unknown unit, accept at least the measurement
                    logger.debug("Could not determine unit for '{}', using default", data.getUnit());
                    result = new QuantityType<>(bd, SmartHomeUnits.ONE);
                }

                logger.debug("State: '{}'", result);
            }
        }
    }

    return result;
}

From source file:com.cartmatic.estore.common.helper.ConfigUtil.java

public BigDecimal getShopPointUseGiftPercent() {
    BigDecimal shopPointUseGiftPercent = new BigDecimal(getConfigAsInt("ShopPointUseGiftPercent", 10));
    shopPointUseGiftPercent = shopPointUseGiftPercent.divide(new BigDecimal(100));
    return shopPointUseGiftPercent;
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Generates FIX <code>Message</code> objects that contain execution reports for partial and/or
 * complete fills of the given order./*from  www  .  j a v  a2 s.  c  om*/
 *
 * <p>The number of objects returned can be adjusted by changing the value of {@link #executionReportMultiplicity}.
 * Whether or not the list partially or fully fills the given order can be adjusted by changing the
 * value of {@link MockRecorderModule#shouldFullyFillOrders}.
 *
 * @param inOrder an <code>OrderSingle</code> value
 * @return a <code>List&lt;Message&gt;</code> value
 * @throws Exception if an error occurs
 */
protected static List<Message> generateFixExecutionReports(OrderSingle inOrder) throws Exception {
    int multiplicity = executionReportMultiplicity;
    List<Message> reports = new ArrayList<Message>();
    if (inOrder.getQuantity() != null) {
        BigDecimal totalQuantity = new BigDecimal(inOrder.getQuantity().toString());
        BigDecimal lastQuantity = BigDecimal.ZERO;
        for (int iteration = 0; iteration < multiplicity - 1; iteration++) {
            BigDecimal thisQuantity = totalQuantity
                    .subtract(totalQuantity.divide(new BigDecimal(Integer.toString(multiplicity))));
            totalQuantity = totalQuantity.subtract(thisQuantity);
            Message rawExeReport = generateFixExecutionReport(inOrder, OrdStatus.PARTIALLY_FILLED, thisQuantity,
                    lastQuantity, FIXVersion.FIX44);
            reports.add(rawExeReport);
            lastQuantity = thisQuantity;
        }
        Message rawExeReport = generateFixExecutionReport(inOrder,
                MockRecorderModule.shouldFullyFillOrders ? OrdStatus.FILLED : OrdStatus.PARTIALLY_FILLED,
                totalQuantity, lastQuantity, FIXVersion.FIX44);
        reports.add(rawExeReport);
    }
    return reports;
}

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

/**
 * Reduce value to the interval [-Pi/2,Pi/2].
 *
 * @param x The original value/*from w  w  w .j  a va 2 s. co  m*/
 * @return The value modulo pi, shifted to the interval from -Pi/2 to Pi/2.
 */
static public BigDecimal modpi(BigDecimal x) {
    /* write x= pi*k+r with the precision in r defined by the precision of x and not
     * compromised by the precision of pi, so the ulp of pi*k should match the ulp of x.
     * First getFloat a guess of k to figure out how many digits of pi are needed.
     */
    int k = (int) (x.doubleValue() / Math.PI);
    /* want to have err(pi*k)< err(x)=x.ulp/2, so err(pi) = err(x)/(2k) with two safety digits
     */

    double errpi;

    if (k != 0) {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue() / k);
    } else {
        errpi = 0.5 * Math.abs(x.ulp().doubleValue());
    }
    MathContext mc = new MathContext(2 + err2prec(3.1416, errpi));
    BigDecimal onepi = pi(mc);
    BigDecimal pihalf = onepi.divide(new BigDecimal(2));
    /* Delegate the actual operation to the BigDecimal class, which may return
     * a negative value of x was negative .
     */
    BigDecimal res = x.remainder(onepi);

    if (res.compareTo(pihalf) > 0) {
        res = res.subtract(onepi);
    } else if (res.compareTo(pihalf.negate()) < 0) {
        res = res.add(onepi);
    }
    /* The actual precision is set by the input value, its absolute value of x.ulp()/2.
     */
    mc = new MathContext(err2prec(res.doubleValue(), x.ulp().doubleValue() / 2.));

    return res.round(mc);

}

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

/**
 * The inverse trigonometric tangent./* w w w  .  j  a  v a 2s  . c o  m*/
 *
 * @param x the argument.
 * @return the principal value of arctan(x) in radians in the range -pi/2 to +pi/2.
 */
static public BigDecimal atan(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return atan(x.negate()).negate();

    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else if (x.doubleValue() > 0.7 && x.doubleValue() < 3.0) {
        /* Abramowitz-Stegun 4.4.34 convergence acceleration
         * 2*arctan(x) = arctan(2x/(1-x^2)) = arctan(y). x=(sqrt(1+y^2)-1)/y
         * This maps 0<=y<=3 to 0<=x<=0.73 roughly. Temporarily with 2 protectionist digits.
         */
        BigDecimal y = scalePrec(x, 2);
        BigDecimal newx = divideRound(hypot(1, y).subtract(BigDecimal.ONE), y);
        /* intermediate result with too optimistic error estimate*/
        BigDecimal resul = multiplyRound(atan(newx), 2);
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp. */

        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));
        MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    } else if (x.doubleValue() < 0.71) {
        /* Taylor expansion around x=0; Abramowitz-Stegun 4.4.42 */
        final BigDecimal xhighpr = scalePrec(x, 2);
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate();
        BigDecimal resul = xhighpr.plus();
        /* signed x^(2i+1) */
        BigDecimal xpowi = xhighpr;
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.
         */

        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));

        for (int i = 1;; i++) {
            xpowi = multiplyRound(xpowi, xhighprSq);
            BigDecimal c = divideRound(xpowi, 2 * i + 1);
            resul = resul.add(c);

            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }

        }
        MathContext mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    } else {
        /* Taylor expansion around x=infinity; Abramowitz-Stegun 4.4.42 */
        /* absolute error in the result is errx/(1+x^2), where errx = half of the ulp.
         */
        double eps = x.ulp().doubleValue() / (2.0 * Math.hypot(1.0, x.doubleValue()));
        /* start with the term pi/2; gather its precision relative to the expected result
         */
        MathContext mc = new MathContext(2 + err2prec(3.1416, eps));
        BigDecimal onepi = pi(mc);
        BigDecimal resul = onepi.divide(new BigDecimal(2));
        final BigDecimal xhighpr = divideRound(-1, scalePrec(x, 2));
        final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr).negate();
        /* signed x^(2i+1) */
        BigDecimal xpowi = xhighpr;

        for (int i = 0;; i++) {
            BigDecimal c = divideRound(xpowi, 2 * i + 1);
            resul = resul.add(c);

            if (Math.abs(c.doubleValue()) < 0.1 * eps) {
                break;
            }
            xpowi = multiplyRound(xpowi, xhighprSq);

        }
        mc = new MathContext(err2prec(resul.doubleValue(), eps));

        return resul.round(mc);

    }
}

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceMatchingServiceImpl.java

protected void validateUnitPrice(ElectronicInvoiceItemHolder itemHolder) {

    PurchaseOrderCostSource costSource = itemHolder.getInvoiceOrderHolder().getPurchaseOrderDocument()
            .getPurchaseOrderCostSource();
    PurchaseOrderItem poItem = itemHolder.getPurchaseOrderItem();
    ElectronicInvoiceOrderHolder orderHolder = itemHolder.getInvoiceOrderHolder();

    String extraDescription = "Invoice Item Line Number:" + itemHolder.getInvoiceItemLineNumber();

    BigDecimal actualVariance = itemHolder.getInvoiceItemUnitPrice().subtract(poItem.getItemUnitPrice());

    BigDecimal lowerPercentage = null;
    if (costSource.getItemUnitPriceLowerVariancePercent() != null) {
        //Checking for lower variance
        lowerPercentage = costSource.getItemUnitPriceLowerVariancePercent();
    } else {/*from w  w w. jav a2  s .  c om*/
        //If the cost source itemUnitPriceLowerVariancePercent is null then
        //we'll use the exact match (100%).
        lowerPercentage = new BigDecimal(100);
    }

    BigDecimal lowerAcceptableVariance = (lowerPercentage.divide(new BigDecimal(100)))
            .multiply(poItem.getItemUnitPrice()).negate();

    if (lowerAcceptableVariance.compareTo(actualVariance) > 0) {
        ElectronicInvoiceRejectReason rejectReason = createRejectReason(
                PurapConstants.ElectronicInvoice.INVOICE_AMT_LESSER_THAN_LOWER_VARIANCE, extraDescription,
                orderHolder.getFileName());
        orderHolder.addInvoiceOrderRejectReason(rejectReason,
                PurapConstants.ElectronicInvoice.RejectDocumentFields.INVOICE_ITEM_UNIT_PRICE,
                PurapKeyConstants.ERROR_REJECT_UNITPRICE_LOWERVARIANCE);
    }

    BigDecimal upperPercentage = null;

    if (costSource.getItemUnitPriceUpperVariancePercent() != null) {
        //Checking for upper variance
        upperPercentage = costSource.getItemUnitPriceUpperVariancePercent();
    } else {
        //If the cost source itemUnitPriceLowerVariancePercent is null then
        //we'll use the exact match (100%).
        upperPercentage = new BigDecimal(100);
    }
    BigDecimal upperAcceptableVariance = (upperPercentage.divide(new BigDecimal(100)))
            .multiply(poItem.getItemUnitPrice());

    if (upperAcceptableVariance.compareTo(actualVariance) < 0) {
        ElectronicInvoiceRejectReason rejectReason = createRejectReason(
                PurapConstants.ElectronicInvoice.INVOICE_AMT_GREATER_THAN_UPPER_VARIANCE, extraDescription,
                orderHolder.getFileName());
        orderHolder.addInvoiceOrderRejectReason(rejectReason,
                PurapConstants.ElectronicInvoice.RejectDocumentFields.INVOICE_ITEM_UNIT_PRICE,
                PurapKeyConstants.ERROR_REJECT_UNITPRICE_UPPERVARIANCE);
    }

}