Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

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

/**
  * ??????/*from   w  ww.j  a v a  2 s  .c om*/
  * 
  * @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.flowzr.budget.holo.widget.CalculatorInput.java

private void doLastOp() {
    isRestart = true;/*from ww w. j a va2  s.  c  om*/
    if (lastOp == '\0' || stack.size() == 1) {
        return;
    }

    String valTwo = stack.pop();
    String valOne = stack.pop();
    switch (lastOp) {
    case '+':
        stack.push(new BigDecimal(valOne).add(new BigDecimal(valTwo)).toPlainString());
        break;
    case '-':
        stack.push(new BigDecimal(valOne).subtract(new BigDecimal(valTwo)).toPlainString());
        break;
    case '*':
        stack.push(new BigDecimal(valOne).multiply(new BigDecimal(valTwo)).toPlainString());
        break;
    case '/':
        BigDecimal d2 = new BigDecimal(valTwo);
        if (d2.intValue() == 0) {
            stack.push("0.0");
        } else {
            stack.push(new BigDecimal(valOne).divide(d2, 2, BigDecimal.ROUND_HALF_UP).toPlainString());
        }
        break;
    default:
        break;
    }
    setDisplay(stack.peek());
    if (isInEquals) {
        stack.push(valTwo);
    }
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode <code>BigDecimal</code>, by XML namespace and tag name, from an
 * XML Element. The children elements of <code>aElement</code> will be
 * searched for the specified <code>aNS</code> namespace URI and the
 * specified <code>aTagName</code>. The first XML element found will be
 * decoded and returned. If no element is found, <code>null</code> is
 * returned.//from   www. j av  a  2  s  .  c o m
 * 
 * @param aElement
 *            XML Element to scan. For example, the element could be
 *            &ltdomain:create&gt
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @return <code>BigDecimal</code> value if found; <code>null</code>
 *         otherwise.
 * @exception EPPDecodeException
 *                Error decoding <code>aElement</code>.
 */
public static BigDecimal decodeBigDecimal(Element aElement, String aNS, String aTagName)
        throws EPPDecodeException {

    Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName);

    BigDecimal retBigDecimal = null;
    if (theElm != null) {
        Node textNode = theElm.getFirstChild();

        // Element does have a text node?
        if (textNode != null) {

            String doubleValStr = textNode.getNodeValue();
            try {

                Double tempDouble = Double.valueOf(doubleValStr);
                retBigDecimal = new BigDecimal(tempDouble.doubleValue());
                retBigDecimal = retBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
            } catch (NumberFormatException e) {
                throw new EPPDecodeException("Can't convert value to Double: " + doubleValStr + e);
            }
        } else {
            throw new EPPDecodeException("Can't decode numeric value from non-existant text node");
        }
    }
    return retBigDecimal;
}

From source file:org.kalypso.model.wspm.tuhh.core.wprof.BCEShapeWPRofContentProvider.java

@Override
public BigDecimal getStation() {
    final double station = getProperty("STATION", Double.class, Double.NaN); //$NON-NLS-1$
    if (Double.isNaN(station) || station < -99990.00)
        return null;

    try {//from   w  ww .  ja v a2 s  . c  o  m
        final double faktorStation = 1;
        return new BigDecimal(station / faktorStation).setScale(4, BigDecimal.ROUND_HALF_UP);
    } catch (final NumberFormatException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.alibaba.rocketmq.tools.command.cluster.CLusterSendMsgRTCommand.java

@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) {
    DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
    defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));

    DefaultMQProducer producer = new DefaultMQProducer(rpcHook);
    producer.setProducerGroup(Long.toString(System.currentTimeMillis()));

    try {/*from   w w w.  j  a  v  a2 s  .  com*/
        defaultMQAdminExt.start();
        producer.start();

        ClusterInfo clusterInfoSerializeWrapper = defaultMQAdminExt.examineBrokerClusterInfo();
        HashMap<String, Set<String>> clusterAddr = clusterInfoSerializeWrapper.getClusterAddrTable();

        Set<String> clusterNames = null;

        long amount = !commandLine.hasOption('a') ? 50 : Long.parseLong(commandLine.getOptionValue('a').trim());

        long size = !commandLine.hasOption('s') ? 128 : Long.parseLong(commandLine.getOptionValue('s').trim());

        long interval = !commandLine.hasOption('i') ? 10
                : Long.parseLong(commandLine.getOptionValue('i').trim());

        boolean printAsTlog = !commandLine.hasOption('p') ? false
                : Boolean.parseBoolean(commandLine.getOptionValue('p').trim());

        String machineRoom = !commandLine.hasOption('m') ? "noname" : commandLine.getOptionValue('m').trim();

        if (commandLine.hasOption('c')) {
            clusterNames = new TreeSet<String>();
            clusterNames.add(commandLine.getOptionValue('c').trim());
        } else {
            clusterNames = clusterAddr.keySet();
        }

        if (!printAsTlog) {
            System.out.printf("%-24s  %-24s  %-4s  %-8s  %-8s%n", //
                    "#Cluster Name", //
                    "#Broker Name", //
                    "#RT", //
                    "#successCount", //
                    "#failCount"//
            );
        }

        while (true) {
            for (String clusterName : clusterNames) {
                Set<String> brokerNames = clusterAddr.get(clusterName);
                if (brokerNames == null) {
                    System.out.printf("cluster [%s] not exist", clusterName);
                    break;
                }

                for (String brokerName : brokerNames) {
                    Message msg = new Message(brokerName,
                            getStringBySize(size).getBytes(MixAll.DEFAULT_CHARSET));
                    long start = 0;
                    long end = 0;
                    long elapsed = 0;
                    int successCount = 0;
                    int failCount = 0;

                    for (int i = 0; i < amount; i++) {
                        start = System.currentTimeMillis();
                        try {
                            producer.send(msg);
                            successCount++;
                            end = System.currentTimeMillis();
                        } catch (Exception e) {
                            failCount++;
                            end = System.currentTimeMillis();
                        }

                        if (i != 0) {
                            elapsed += end - start;
                        }
                    }

                    double rt = (double) elapsed / (amount - 1);
                    if (!printAsTlog) {
                        System.out.printf("%-24s  %-24s  %-8s  %-16s  %-16s%n", //
                                clusterName, //
                                brokerName, //
                                String.format("%.2f", rt), //
                                successCount, //
                                failCount//
                        );
                    } else {
                        System.out
                                .println(String.format("%s|%s|%s|%s|%s", getCurTime(), machineRoom, clusterName,
                                        brokerName, new BigDecimal(rt).setScale(0, BigDecimal.ROUND_HALF_UP)));
                    }

                }

            }

            Thread.sleep(interval * 1000);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        defaultMQAdminExt.shutdown();
        producer.shutdown();
    }
}

From source file:com.salesmanager.core.module.impl.application.currencies.GenericCurrencyModule.java

public String getMeasure(BigDecimal measure, String currencycode) throws Exception {

    NumberFormat nf = null;//from   ww w  .  j a v a 2  s  .c o m

    Locale locale = Locale.US;

    if (this.decimalPoint == ',') {
        locale = Locale.GERMAN;
    }

    nf = NumberFormat.getInstance(locale);

    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    measure.setScale(1, BigDecimal.ROUND_HALF_UP);

    return nf.format(measure);
}

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

/**
 * Getter method for the instance variable {@link #amountRate}.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return value of instance variable {@link #amountRate}
 * @throws EFapsException on error//w ww  .j  a  va 2  s  . c om
 */
public BigDecimal getAmountRate(final Parameter _parameter) throws EFapsException {
    if (this.amountRate == null && this.amount != null && this.rateInfo != null) {
        this.amountRate = this.amount.setScale(12, BigDecimal.ROUND_HALF_UP).divide(getRate(_parameter),
                BigDecimal.ROUND_HALF_UP);
    }
    return this.amountRate;
}

From source file:com.selfsoft.business.action.TbFixEntrustAction.java

public String findTbFixEntrust() {
    if (null == tbFixEntrust) {

        tbFixEntrust = new TbFixEntrust();

        tbFixEntrust.setIsvalid(Constants.ISVALIDVALUE);

        tbFixEntrust.setFixDateStart(CommonMethod.parseStringToDate(
                CommonMethod.parseDateToString(CommonMethod.addDate(new Date(), -14), "yyyy-MM-dd"),
                "yyyy-MM-dd"));

        tbFixEntrust.setFixDateEnd(CommonMethod
                .parseStringToDate(CommonMethod.parseDateToString(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd"));
    }/*from   w w  w.j a va  2s  . c o m*/

    String wjg = request.getParameter("wjg");

    tbFixEntrust.setWjg(wjg);

    String jsqk = request.getParameter("jsqk");

    tbFixEntrust.setJsqk(jsqk);

    List<TbFixEntrust> tbFixEntrustList = tbFixEntrustService.findByTbFixEntrust(tbFixEntrust);

    List<TbFixEntrust> tbFixEntrustListPage = new ArrayList<TbFixEntrust>();

    BigDecimal pjcbTotal = new BigDecimal("0.00");

    if (null != tbFixEntrustList && tbFixEntrustList.size() > 0) {

        for (TbFixEntrust _tbFixEntrust : tbFixEntrustList) {

            _tbFixEntrust.setFixHourTotal(new BigDecimal(
                    tbFixEntrustContentService.countTbFixEnTrustContentByTbFixEntrustId(_tbFixEntrust.getId()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP));

            List<TbMaintainPartContent> tcList = tbMaintainPartContentService
                    .getViewEntrustMaintianContent(_tbFixEntrust.getId());

            if (null != tcList && tcList.size() > 0) {

                _tbFixEntrust.setStockOutPartTotal(
                        new BigDecimal(tcList.get(0).getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));

            }

            _tbFixEntrust.setPjcb(
                    new BigDecimal(statisticsStockInOutService.sumStockDetailByEntrustId(_tbFixEntrust.getId()))
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP));

            pjcbTotal = pjcbTotal.add(_tbFixEntrust.getPjcb());

            _tbFixEntrust.setSolePartTotal(
                    new BigDecimal(tmStockOutService.getTotalPriceByEntrustCode(_tbFixEntrust.getEntrustCode()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP));

            _tbFixEntrust.setAllTotal(_tbFixEntrust.getFixHourTotal()
                    .add(_tbFixEntrust.getStockOutPartTotal().add(_tbFixEntrust.getSolePartTotal())));

            _tbFixEntrust.setZlr(_tbFixEntrust.getFixHourTotal().add(_tbFixEntrust.getStockOutPartTotal()
                    .add(_tbFixEntrust.getSolePartTotal()).subtract(_tbFixEntrust.getPjcb())));

            tbFixEntrustListPage.add(_tbFixEntrust);

        }

    }

    ActionContext.getContext().put("pjcbTotal",
            pjcbTotal.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP));

    ActionContext.getContext().put("tmUserMap", tmUserService.findAllTmUserMap());

    ActionContext.getContext().put("tbFixEntrustList", tbFixEntrustListPage);

    ActionContext.getContext().getSession().put("tbFixEntrustListSession", tbFixEntrustListPage);

    return Constants.SUCCESS;
}

From source file:org.egov.ptis.service.dashboard.PropTaxDashboardService.java

/**
 * Provides State-wise Collection Statistics for Property Tax, Water Charges and Others
 * /*from  w w  w  .j a  va 2  s . co  m*/
 * @return CollectionStats
 */
public TotalCollectionStats getTotalCollectionStats(final HttpServletRequest request) {
    TotalCollectionStats consolidatedCollectionDetails = new TotalCollectionStats();
    // For Property Tax collections
    CollectionStats consolidatedData = new CollectionStats();
    Map<String, BigDecimal> consolidatedColl = collectionIndexElasticSearchService
            .getFinYearsCollByService(COLLECION_BILLING_SERVICE_PT);
    CFinancialYear currFinYear = getCurrentFinancialYear();

    if (!consolidatedColl.isEmpty()) {
        consolidatedData.setCytdColl(consolidatedColl.get("cytdColln"));
        consolidatedData.setLytdColl(consolidatedColl.get("lytdColln"));
    }
    BigDecimal totalDmd = propertyTaxElasticSearchIndexService.getTotalDemand();
    int noOfMonths = DateUtils.noOfMonthsBetween(DateUtils.startOfDay(currFinYear.getStartingDate()),
            new Date()) + 1;
    consolidatedData.setTotalDmd(totalDmd.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
            .multiply(BigDecimal.valueOf(noOfMonths)));
    if (consolidatedData.getTotalDmd().compareTo(BigDecimal.ZERO) > 0)
        consolidatedData.setPerformance(consolidatedData.getCytdColl().multiply(BIGDECIMAL_100)
                .divide(consolidatedData.getTotalDmd(), 1, BigDecimal.ROUND_HALF_UP));
    if (consolidatedData.getLytdColl().compareTo(BigDecimal.ZERO) > 0)
        consolidatedData.setLyVar((consolidatedData.getCytdColl().subtract(consolidatedData.getLytdColl())
                .multiply(BIGDECIMAL_100)).divide(consolidatedData.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP));
    consolidatedCollectionDetails.setPropertyTax(consolidatedData);

    // For Water Tax collections
    consolidatedData = new CollectionStats();
    consolidatedColl = collectionIndexElasticSearchService
            .getFinYearsCollByService(COLLECION_BILLING_SERVICE_WTMS);
    if (!consolidatedColl.isEmpty()) {
        consolidatedData.setCytdColl(consolidatedColl.get("cytdColln"));
        consolidatedData.setLytdColl(consolidatedColl.get("lytdColln"));
    }
    BigDecimal totalDemandValue = getWaterChargeTotalDemand(request);
    int numberOfMonths = DateUtils.noOfMonthsBetween(DateUtils.startOfDay(currFinYear.getStartingDate()),
            new Date()) + 1;
    consolidatedData.setTotalDmd(totalDemandValue.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
            .multiply(BigDecimal.valueOf(numberOfMonths)));
    if (consolidatedData.getTotalDmd().compareTo(BigDecimal.ZERO) > 0)
        consolidatedData.setPerformance(consolidatedData.getCytdColl().multiply(BIGDECIMAL_100)
                .divide(consolidatedData.getTotalDmd(), 1, BigDecimal.ROUND_HALF_UP));
    if (consolidatedData.getLytdColl().compareTo(BigDecimal.ZERO) > 0)
        consolidatedData.setLyVar((consolidatedData.getCytdColl().subtract(consolidatedData.getLytdColl())
                .multiply(BIGDECIMAL_100)).divide(consolidatedData.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP));
    consolidatedCollectionDetails.setWaterTax(consolidatedData);

    // Other collections - temporarily set to 0
    consolidatedData = new CollectionStats();
    consolidatedData.setCytdColl(BigDecimal.ZERO);
    consolidatedData.setTotalDmd(BigDecimal.ZERO);
    consolidatedData.setLytdColl(BigDecimal.ZERO);
    consolidatedData.setPerformance(BigDecimal.ZERO);
    consolidatedData.setLyVar(BigDecimal.ZERO);
    consolidatedCollectionDetails.setOthers(consolidatedData);

    return consolidatedCollectionDetails;
}

From source file:com.sciaps.model.RegionsTableModel.java

public void doCalculate(int type) {
    if (callback_ != null) {
        double retval;
        double waveLength;
        double regionWidth;

        for (RegionMarkerItem markerItem : data_) {
            regionWidth = markerItem.getMax() - markerItem.getMin();
            waveLength = markerItem.getMin() + regionWidth / 2;
            retval = callback_.getIntensityOfLine(type, waveLength, regionWidth);

            // The -1 value identicate no shot is selected to do the calculation. 
            // Therefore, break out of this for loop
            if (retval == -1) {
                break;
            }/* w w w.  j  a  v  a 2 s .  c  om*/

            retval = (new BigDecimal(retval)).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
            markerItem.setValue(retval);
        }

        fireTableDataChanged();
    }
}