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, int scale, RoundingMode roundingMode) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose scale is as specified.

Usage

From source file:org.yes.cart.payment.impl.PostFinancePaymentGatewayImpl.java

private void populateItems(final Payment payment, final Map<String, String> params) {

    BigDecimal totalItemsGross = Total.ZERO;

    for (final PaymentLine item : payment.getOrderItems()) {
        totalItemsGross = totalItemsGross.add(item.getQuantity().multiply(item.getUnitPrice()));
    }/*from w  ww . ja v  a2 s.c  om*/

    final int it = payment.getOrderItems().size();

    BigDecimal orderDiscountRemainder = Total.ZERO;
    BigDecimal orderDiscountPercent = Total.ZERO;
    final BigDecimal payGross = payment.getPaymentAmount();
    if (payGross.compareTo(totalItemsGross) < 0) {
        orderDiscountRemainder = totalItemsGross.subtract(payGross);
        orderDiscountPercent = orderDiscountRemainder.divide(totalItemsGross, 10, RoundingMode.HALF_UP);
    }

    int i = 1;
    boolean hasOrderDiscount = MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, Total.ZERO);
    for (final PaymentLine item : payment.getOrderItems()) {

        final BigDecimal itemGrossAmount = item.getUnitPrice().multiply(item.getQuantity())
                .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP);
        params.put("ITEMID" + i,
                item.getSkuCode().length() > ITEMID ? item.getSkuCode().substring(0, ITEMID - 1) + "~"
                        : item.getSkuCode());
        params.put("ITEMNAME" + i,
                item.getSkuName().length() > ITEMNAME ? item.getSkuName().substring(0, ITEMNAME - 1) + "~"
                        : item.getSkuName());
        params.put("ITEMQUANT" + i, item.getQuantity().toPlainString());
        if (hasOrderDiscount && MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, Total.ZERO)
                && MoneyUtils.isFirstBiggerThanSecond(itemGrossAmount, Total.ZERO)) {
            BigDecimal discount;
            if (i == it) {
                // last item
                discount = orderDiscountRemainder;
            } else {
                BigDecimal itemDiscount = itemGrossAmount.multiply(orderDiscountPercent)
                        .setScale(Total.ZERO.scale(), RoundingMode.CEILING);
                if (MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, itemDiscount)) {
                    discount = itemDiscount;
                    orderDiscountRemainder = orderDiscountRemainder.subtract(itemDiscount);
                } else {
                    discount = orderDiscountRemainder;
                    orderDiscountRemainder = Total.ZERO;
                }

            }
            final BigDecimal scaleRate = discount.divide(itemGrossAmount.subtract(discount), 10,
                    RoundingMode.CEILING);
            final BigDecimal scaledTax = item.getTaxAmount().multiply(scaleRate).setScale(Total.ZERO.scale(),
                    RoundingMode.FLOOR);
            params.put("ITEMDISCOUNT" + i, discount.toPlainString());
            params.put("ITEMPRICE" + i, itemGrossAmount.subtract(discount).subtract(item.getTaxAmount())
                    .add(scaledTax).toPlainString());
            params.put("ITEMVAT" + i, item.getTaxAmount().subtract(scaledTax).toPlainString());
        } else {
            params.put("ITEMPRICE" + i, itemGrossAmount.subtract(item.getTaxAmount()).toPlainString());
            params.put("ITEMVAT" + i, item.getTaxAmount().toPlainString());
        }
        i++;
    }
}

From source file:com.eryansky.common.utils.SysUtils.java

/**
  * ??????//from  www  . j a v  a2  s  . c  o  m
  * 
  * @param v
  *            ??
  * @param scale
  *            ????
  * @return ??
  */
 public static double round(double v, int scale) {
     if (scale < 0) {
         throw new IllegalArgumentException("The scale must be a positive integer or zero");
     }
     BigDecimal b = new BigDecimal(Double.toString(v));
     BigDecimal one = new BigDecimal("1");
     return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
 }

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

@Override
public Map<Integer, BigDecimal> findMainBedragen(List<? extends Bedragen> bedragen, String Month) {
    SimpleDateFormat dt = new SimpleDateFormat("MM/yyyy");
    Map<GroepenSrvPojo, BigDecimal> mainBedragenPerGroup = new HashMap<GroepenSrvPojo, BigDecimal>();

    for (Bedragen bedrag : bedragen) {
        if (dt.format(bedrag.getDatum()).equals(Month)) {
            GroepenSrvPojo mainGroup = new GroepenSrvPojo(GroepenSrvImpl.getHoofdGroep(bedrag.getGroep()));
            if (mainBedragenPerGroup.containsKey(mainGroup)) {
                BigDecimal ammount = mainBedragenPerGroup.get(mainGroup);
                if (bedrag.getGroep().getNegatief().equals(1)) {
                    ammount = ammount.add(bedrag.getBedrag());
                } else {
                    ammount = ammount.subtract(bedrag.getBedrag());
                }//  w w w .  jav a2 s  . c om
                mainBedragenPerGroup.put(mainGroup, ammount);
            } else {
                if (bedrag.getGroep().getNegatief().equals(1)) {
                    mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag());
                } else {
                    mainBedragenPerGroup.put(mainGroup, bedrag.getBedrag().multiply(new BigDecimal(-1)));
                }
            }
        }
    }

    BigDecimal average = new BigDecimal(0);
    for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) {
        average = average.add((BigDecimal) bedrag.getValue());
    }
    average = average.divide(new BigDecimal(mainBedragenPerGroup.size()), 2, RoundingMode.HALF_UP);

    Map<Integer, BigDecimal> result = new HashMap<Integer, BigDecimal>();

    result.put(0, average);

    for (Map.Entry bedrag : mainBedragenPerGroup.entrySet()) {
        result.put(((GroepenSrvPojo) bedrag.getKey()).getPk_id(), (BigDecimal) bedrag.getValue());
    }

    return result;
}

From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java

private String executePerformanceTestWorkers() throws CompositeException {
    try {//from   w  w  w  .  ja  v a2  s. c  o  m
        // Create all the connections
        Worker[] workers = new Worker[perfTestThreads];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker();
        }
        // Pause in between query executions
        Thread.sleep(perfTestSleepExec * 1000);

        // Start the clock
        long startTime = System.currentTimeMillis();
        endTime = startTime + perfTestDuration * 1000;

        // Start the workers
        for (int i = 0; i < workers.length; i++) {
            workers[i].start();
        }

        // Output the Header Rows
        String content = CommonUtils.lpad(HEADER, 7, padChar) + logDelim
                + CommonUtils.rpad("Threads=" + perfTestThreads, 12, padChar) + logDelim
                + CommonUtils.rpad("Duration (s)=" + perfTestDuration, 17, padChar) + logDelim
                + CommonUtils.rpad("Print Sleep (s)=" + perfTestSleepPrint, 19, padChar) + logDelim
                + CommonUtils.rpad("Exec Sleep (s)=" + perfTestSleepExec, 18, padChar) + logDelim + logDelim
                + logDelim + logDelim;

        RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
        StringBuffer buf = new StringBuffer();
        buf.append(content + "\n");

        content = CommonUtils.lpad(HEADER, 8, padChar) + logDelim + CommonUtils.rpad("Execs", 12, padChar)
                + logDelim + CommonUtils.rpad("Execs/sec", 12, padChar) + logDelim
                + CommonUtils.rpad("Rows/exec", 12, padChar) + logDelim
                + CommonUtils.rpad("Latency (ms)", 13, padChar) + logDelim
                + CommonUtils.rpad("1st row (ms)", 13, padChar) + logDelim
                + CommonUtils.rpad("Duration (ms)", 14, padChar) + logDelim + logDelim;

        RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
        buf.append(content + "\n");

        // Initialize the totals before each query execution.
        numStatExecs.set(0);
        execsTotal = 0;
        tpsTotal = new BigDecimal(0);
        rptTotal = new BigDecimal(0);
        latTotal = new BigDecimal(0);
        frTotal = new BigDecimal(0);
        durTotal = new BigDecimal(0);

        /* Safeguard: determine the number of loops by taking the "total duration" divided by the "print stat sleep interval"
         *   This is important because sometimes the timing is off when the end time is calculated and when worker threads are 
         *   still running.  The issue is pointed out below (-->) when there is an extra line printed that throws off the stats.
         *   
         *    HEADER|Threads=1   |Duration (s)=10  |Print Sleep (s)=5  |Exec Sleep (s)=0  ||||
         *    HEADER|Execs       |Execs/sec   |Rows/exec   |Latency (ms) |1st row (ms) |Duration (ms) ||
         *    DETAIL|4780        |957.91      |1.00        |1.04         |1.03         |4990.00             ||
         *    DETAIL|5146        |1027.96     |1.00        |0.97         |0.96         |5006.00             ||
         * -->DETAIL|11          |2.19        |1.00        |0.90         |0.90         |5018.00             ||
         *    TOTALS|3312.33     |662.68      |1.00        |0.97         |0.96         |5004.66             ||
         */
        int totalExecLoops = perfTestDuration / perfTestSleepPrint;

        // Print stats periodically
        errorFound = false;
        int loopCounter = 0;
        while (System.currentTimeMillis() < endTime && !errorFound && loopCounter < totalExecLoops) {
            Thread.sleep(perfTestSleepPrint * 1000);
            content = printStats(startTime);
            if (content != null)
                buf.append(content);

            // Reset print stat counters              
            numExecs.set(0);
            numLatency.set(0);
            firstRowLatency.set(0);
            numRows.set(0);
            startTime = System.currentTimeMillis();
            loopCounter++;
        }

        // Wait for the workers to finish
        for (int i = 0; i < workers.length; i++) {
            workers[i].join();
        }

        // Print stats
        /*
         * This is @deprecated as it was determined that the last stat line was inconsistent and throwing off the numbers
        content = printStats(startTime);
        if (content != null)
           buf.append(content);
        */

        // Calculate the Total Average Stats for each run and output as a TOTALS line
        if (numStatExecs.get() > 0) {
            // Calculate total average executions
            BigDecimal execAvg = new BigDecimal(execsTotal);
            execAvg = execAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            execAvg = execAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average execs/sec or tps
            BigDecimal tpsAvg = tpsTotal;
            tpsAvg = tpsAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            tpsAvg = tpsAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Rows per Execution
            BigDecimal rptAvg = rptTotal;
            rptAvg = rptAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            rptAvg = rptAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Latency
            BigDecimal latAvg = latTotal;
            latAvg = latAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            latAvg = latAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average First Row Latency
            BigDecimal frAvg = frTotal;
            frAvg = frAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            frAvg = frAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Calculate total average Duration
            BigDecimal durAvg = durTotal;
            durAvg = durAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR);
            durAvg = durAvg.setScale(2, BigDecimal.ROUND_DOWN);

            // Print out the summary Totals line
            content = CommonUtils.lpad(TOTALS, 8, padChar) + logDelim
                    + CommonUtils.rpad("" + execAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + tpsAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + rptAvg, 12, padChar) + logDelim
                    + CommonUtils.rpad("" + latAvg, 13, padChar) + logDelim
                    + CommonUtils.rpad("" + frAvg, 13, padChar) + logDelim
                    + CommonUtils.rpad("" + durAvg, 20, padChar) + logDelim + logDelim;

            RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, "");
            buf.append(content + "\n");
        }

        return buf.toString();
    } catch (Exception e) {
        throw new ApplicationException(e);
    }
}

From source file:pyromaniac.Algorithm.QuinceOUFrequencyTable.java

private BigDecimal[] _calculateProbabilitiesHelper(int mode) {
    BigDecimal sd = new BigDecimal("0.04").add(new BigDecimal(mode).multiply(new BigDecimal("0.03")));
    BigDecimal modeBD = new BigDecimal(mode);

    BigDecimal lowerBound = modeBD.subtract(new BigDecimal(SUBTRACT_FOR_LB)).setScale(SCALE,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal upperBound = modeBD.add(new BigDecimal(ADD_FOR_UB)).setScale(SCALE, BigDecimal.ROUND_HALF_UP);

    NormalDistribution norm = new NormalDistribution(mode, sd.doubleValue());

    try {/*  w w w .j  ava 2  s .  co  m*/
        BigDecimal probLessThan = new BigDecimal(norm.cumulativeProbability(lowerBound.doubleValue()))
                .setScale(SCALE, BigDecimal.ROUND_HALF_UP);
        BigDecimal probMoreThan = new BigDecimal("1")
                .subtract(new BigDecimal(norm.cumulativeProbability(upperBound.doubleValue())))
                .setScale(SCALE, BigDecimal.ROUND_HALF_UP);
        BigDecimal probEqualTo = new BigDecimal("1").subtract(probLessThan).subtract(probMoreThan)
                .setScale(SCALE, BigDecimal.ROUND_HALF_UP);

        BigDecimal totalProb = probLessThan.add(probEqualTo).add(probMoreThan).setScale(SCALE,
                BigDecimal.ROUND_HALF_UP);

        if (!totalProb.equals(new BigDecimal("1").setScale(SCALE, BigDecimal.ROUND_HALF_UP))) {
            probLessThan = probLessThan.divide(totalProb, SCALE, BigDecimal.ROUND_HALF_UP);
            probMoreThan = probMoreThan.divide(totalProb, SCALE, BigDecimal.ROUND_HALF_UP);
            probEqualTo = probEqualTo.divide(totalProb, SCALE, BigDecimal.ROUND_HALF_UP);
        }

        BigDecimal[] probs = { probLessThan, probEqualTo, probMoreThan };
        return probs;
    } catch (MathIllegalStateException me) {
        me.getStackTrace();
    }
    return null;
}

From source file:org.openbravo.costing.CostingRuleProcess.java

private void updateInventoriesCostAndProcessInitInventories(String ruleId, Date startingDate,
        boolean existsPreviousRule) {
    CostingRule rule = OBDal.getInstance().get(CostingRule.class, ruleId);
    for (CostingRuleInit cri : rule.getCostingRuleInitList()) {
        for (InventoryCountLine icl : cri.getCloseInventory().getMaterialMgmtInventoryCountLineList()) {
            MaterialTransaction trx = getInventoryLineTransaction(icl);
            // Remove 1 second from transaction date to ensure that cost is calculated with previous
            // costing rule.
            trx.setTransactionProcessDate(DateUtils.addSeconds(startingDate, -1));
            BigDecimal trxCost = BigDecimal.ZERO;
            BigDecimal cost = null;
            Currency cur = FinancialUtils.getLegalEntityCurrency(trx.getOrganization());
            if (existsPreviousRule) {
                trxCost = CostingUtils.getTransactionCost(trx, startingDate, true, cur);
                if (trx.getMovementQuantity().compareTo(BigDecimal.ZERO) != 0) {
                    cost = trxCost.divide(trx.getMovementQuantity().abs(), cur.getCostingPrecision().intValue(),
                            RoundingMode.HALF_UP);
                }/*  w w w . j  av  a2  s . c o m*/
            } else {
                // Insert transaction cost record big ZERO cost.
                cur = trx.getClient().getCurrency();
                TransactionCost transactionCost = OBProvider.getInstance().get(TransactionCost.class);
                transactionCost.setInventoryTransaction(trx);
                transactionCost.setCostDate(trx.getTransactionProcessDate());
                transactionCost.setClient(trx.getClient());
                transactionCost.setOrganization(trx.getOrganization());
                transactionCost.setCost(BigDecimal.ZERO);
                transactionCost.setCurrency(trx.getClient().getCurrency());
                transactionCost.setAccountingDate(trx.getGoodsShipmentLine() != null
                        ? trx.getGoodsShipmentLine().getShipmentReceipt().getAccountingDate()
                        : trx.getMovementDate());
                List<TransactionCost> trxCosts = trx.getTransactionCostList();
                trxCosts.add(transactionCost);
                trx.setTransactionCostList(trxCosts);
                OBDal.getInstance().save(trx);
            }

            trx.setCostCalculated(true);
            trx.setCostingStatus("CC");
            trx.setCurrency(cur);
            trx.setTransactionCost(trxCost);
            OBDal.getInstance().save(trx);
            InventoryCountLine initICL = getInitIcl(cri.getInitInventory(), icl);
            initICL.setCost(cost);
            OBDal.getInstance().save(initICL);
        }
        OBDal.getInstance().flush();
        new InventoryCountProcess().processInventory(cri.getInitInventory(), false);
    }
    if (!existsPreviousRule) {
        updateInitInventoriesTrxDate(startingDate, ruleId);
    }
}

From source file:mx.edu.um.mateo.inventario.dao.impl.EntradaDaoHibernate.java

private BigDecimal costoPromedio(LoteEntrada lote) {
    Producto producto = lote.getProducto();

    BigDecimal cantidad = lote.getCantidad();
    BigDecimal viejoBalance = producto.getPrecioUnitario().multiply(producto.getExistencia());
    BigDecimal nuevoBalance = lote.getPrecioUnitario().multiply(cantidad);

    BigDecimal balanceTotal = viejoBalance.add(nuevoBalance);
    BigDecimal articulos = cantidad.add(producto.getExistencia());
    return balanceTotal.divide(articulos, 10, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

public void makeOverlayImage(ArrayList gates, int x, int y, int xAxis, int yAxis) {
    //convert gate to chart x,y path

    Gate gate;/*from w  ww  . java  2  s.  c om*/
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get

    int total = 0;
    int gated = 0;
    int selected = 0;
    int gatedSelected = 0;

    int gatecount = gates.size();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> result = new ArrayList<MicroObject>();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(xAxis, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(yAxis, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
            }
            ;

            Overlay overlay = new Overlay();

            int count = 0;
            BufferedImage placeholder = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            ImageStack gateOverlay = new ImageStack(impoverlay.getWidth(), impoverlay.getHeight());

            selected = getSelectedObjects();

            total = volumes.size();

            gated = getGatedObjects(impoverlay);

            gatedSelected = getGatedSelected(impoverlay);

            for (int i = 0; i <= impoverlay.getNSlices(); i++) {
                BufferedImage selections = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                        BufferedImage.TYPE_INT_ARGB);

                Graphics2D g2 = selections.createGraphics();

                ImageRoi ir = new ImageRoi(0, 0, placeholder);
                ListIterator<MicroObject> vitr = result.listIterator();

                while (vitr.hasNext()) {
                    try {
                        MicroObject vol = (MicroObject) vitr.next();

                        int[] x_pixels = vol.getXPixelsInRegion(i);
                        int[] y_pixels = vol.getYPixelsInRegion(i);

                        for (int c = 0; c < x_pixels.length; c++) {

                            g2.setColor(gate.getColor());
                            g2.drawRect(x_pixels[c], y_pixels[c], 1, 1);
                        }
                        ir = new ImageRoi(0, 0, selections);
                        count++;

                    } catch (NullPointerException e) {
                    }
                }

                ir.setPosition(i);
                ir.setOpacity(0.4);
                overlay.add(ir);

                gateOverlay.addSlice(ir.getProcessor());

                java.awt.Font f = new Font("Arial", Font.BOLD, 12);
                BigDecimal percentage = new BigDecimal(selected);
                BigDecimal totalBD = new BigDecimal(total);
                percentage = percentage.divide(totalBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGated = new BigDecimal(gated);
                BigDecimal totalGatedBD = new BigDecimal(total);
                percentageGated = percentageGated.divide(totalGatedBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGatedSelected = new BigDecimal(gatedSelected);
                BigDecimal totalGatedSelectedBD = new BigDecimal(total);
                percentageGatedSelected = percentageGatedSelected.divide(totalGatedSelectedBD, 4,
                        BigDecimal.ROUND_UP);

                // System.out.println("PROFILING: gate fraction: " + percentage.toString());
                if (impoverlay.getWidth() > 256) {

                    TextRoi textTotal = new TextRoi(5, 10,
                            selected + "/" + total + " gated (" + 100 * percentage.doubleValue() + "%)");

                    if (gated > 0) {
                        textTotal = new TextRoi(5, 10, selected + "/" + total + " total ("
                                + 100 * percentage.doubleValue() + "%)" + "; " + gated + "/" + total + " roi ("
                                + 100 * percentageGated.doubleValue() + "%)" + "; " + gatedSelected + "/"
                                + total + " overlap (" + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                    }
                    //TextRoi textImageGated = new TextRoi(5, 18, selected + "/" + total + " gated objects (" + 100 * percentage.doubleValue() + "%)", f);
                    textTotal.setPosition(i);
                    //textImageGated.setPosition(i);
                    overlay.add(textTotal);
                } else {
                    f = new Font("Arial", Font.PLAIN, 10);
                    TextRoi line1 = new TextRoi(5, 5,
                            selected + "/" + total + " gated" + "(" + 100 * percentage.doubleValue() + "%)", f);
                    overlay.add(line1);
                    if (gated > 0) {
                        f = new Font("Arial", Font.PLAIN, 10);
                        TextRoi line2 = new TextRoi(5, 18,
                                gated + "/" + total + " roi (" + 100 * percentageGated.doubleValue() + "%)", f);
                        overlay.add(line2);
                        TextRoi line3 = new TextRoi(5, 31, gatedSelected + "/" + total + " overlap ("
                                + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                        overlay.add(line3);
                    }
                    line1.setPosition(i);

                }
            }
            impoverlay.setOverlay(overlay);

            //ImagePlus gateMaskImage = new ImagePlus("gates", gateOverlay);

            //gateMaskImage.show();

            gate.setGateOverlayStack(gateOverlay);

        }

        impoverlay.draw();
        impoverlay.setTitle(this.getTitle());

        if (impoverlay.getDisplayMode() != IJ.COMPOSITE) {
            impoverlay.setDisplayMode(IJ.COMPOSITE);
        }

        if (impoverlay.getSlice() == 1) {
            impoverlay.setZ(Math.round(impoverlay.getNSlices() / 2));
        } else {
            impoverlay.setSlice(impoverlay.getSlice());
        }
        impoverlay.show();
    }
}

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

@Override
public BigDecimal getPercentageAdvanceMeasurement(AdvanceMeasurement advanceMeasurement) {
    AdvanceAssignment assignment = advanceMeasurement.getAdvanceAssignment();
    if (assignment == null) {
        return BigDecimal.ZERO;
    }/*from w  ww  .  j  a va 2  s  .c o m*/

    BigDecimal maxValue;
    if (assignment instanceof IndirectAdvanceAssignment) {

        maxValue = orderElement.calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) assignment)
                .getMaxValue();
    } else {
        maxValue = ((DirectAdvanceAssignment) assignment).getMaxValue();
    }

    if (maxValue.compareTo(BigDecimal.ZERO) <= 0) {
        return BigDecimal.ZERO;
    }

    BigDecimal value = advanceMeasurement.getValue();
    if (value == null) {
        return BigDecimal.ZERO;
    }

    BigDecimal division = value.divide(maxValue.setScale(2), 4, RoundingMode.DOWN);
    return (division.multiply(new BigDecimal(100))).setScale(2, RoundingMode.DOWN);

}

From source file:org.openvpms.archetype.rules.product.ProductPriceRules.java

/**
 * Calculates a product markup using the following formula:
 * <p/>/*from w  ww.  j  a  v  a2  s  .c o m*/
 * {@code markup = ((price / (cost * ( 1 + tax/100))) - 1) * 100}
 *
 * @param product  the product
 * @param cost     the product cost
 * @param price    the price
 * @param practice the <em>party.organisationPractice</em> used to determine product taxes
 * @return the markup
 * @throws ArchetypeServiceException for any archetype service error
 */
public BigDecimal getMarkup(Product product, BigDecimal cost, BigDecimal price, Party practice) {
    BigDecimal markup = ZERO;
    if (cost.compareTo(ZERO) != 0) {
        BigDecimal taxRate = ZERO;
        if (product != null) {
            taxRate = getTaxRate(product, practice);
        }
        markup = price.divide(cost.multiply(ONE.add(taxRate)), 3, RoundingMode.HALF_UP).subtract(ONE)
                .multiply(ONE_HUNDRED);
        if (markup.compareTo(ZERO) < 0) {
            markup = ZERO;
        }
    }
    return markup;
}