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.example.demo.TestBase.java

public double getRandomPrice() {
    return new BigDecimal(Math.random() * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}

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

/**
 * Method is executed on update trigger for the amount field in the debit
 * and credit table inside the transaction form.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return list for update trigger/* w w w .j  a va 2  s .  c  o m*/
 * @throws EFapsException on error
 */
public Return update4Amount(final Parameter _parameter) throws EFapsException {
    final Return retVal = new Return();
    try {
        final String postfix = getProperty(_parameter, "TypePostfix");
        final String[] amounts = _parameter.getParameterValues("amount_" + postfix);
        final String[] rates = _parameter.getParameterValues("rate_" + postfix);
        final String[] ratesInv = _parameter.getParameterValues("rate_" + postfix + RateUI.INVERTEDSUFFIX);

        final int pos = getSelectedRow(_parameter);
        final DecimalFormat rateFormater = NumberFormatter.get().getFormatter(0, 8);
        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();
        final BigDecimal amount = amounts[pos].isEmpty() ? BigDecimal.ZERO
                : (BigDecimal) rateFormater.parse(amounts[pos]);
        BigDecimal rate = rates[pos].isEmpty() ? BigDecimal.ZERO : (BigDecimal) rateFormater.parse(rates[pos]);
        final boolean rateInv = "true".equalsIgnoreCase(ratesInv[pos]);
        if (rateInv && rate.compareTo(BigDecimal.ZERO) != 0) {
            rate = BigDecimal.ONE.divide(rate, 12, BigDecimal.ROUND_HALF_UP);
        }
        final List<Map<String, String>> list = new ArrayList<>();
        final Instance periodInstance = new Period().evaluateCurrentPeriod(_parameter);

        final BigDecimal sum = getSum4UI(_parameter, postfix, null, null);
        final String postfix2 = "Debit".equals(postfix) ? "Credit" : "Debit";
        final BigDecimal sum2 = getSum4UI(_parameter, postfix2, null, null);
        final String sumStr = formater.format(sum) + " " + new Period().getCurrency(periodInstance).getSymbol();
        final String sumStr2 = formater.format(sum.subtract(sum2).abs()) + " "
                + new Period().getCurrency(periodInstance).getSymbol();

        final Map<String, String> map = new HashMap<>();
        map.put("sum" + postfix, sumStr);
        map.put("amountRate_" + postfix,
                formater.format(amount.setScale(8).divide(rate, BigDecimal.ROUND_HALF_UP)));
        map.put("sumTotal", sumStr2);
        list.add(map);
        retVal.put(ReturnValues.VALUES, list);
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Amount.ParseException", e);
    }
    return retVal;
}

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

/**
 * Method for recalculate and return string.
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @param _docInst Instance of the document selected.
 * @return String./*from   w  w  w . j a  v  a 2s.  co m*/
 * @throws EFapsException on error.
 */
protected String getRecalculateInfo(final Parameter _parameter, final Instance _docInst) throws EFapsException {
    final StringBuilder html = new StringBuilder();
    final PrintQuery print = new PrintQuery(_docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

    final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal);
    final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal);
    final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name);
    final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
    final Instance currentInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
    final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst);
    final CurrencyInst curr = new CurrencyInst(currentInst);

    final PriceUtil priceUtil = new PriceUtil();
    final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
    final BigDecimal rate = rates[2];

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);

    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");

    html.append("<table>").append("<tr>").append("<td>").append(DBProperties.getProperty("Sales_Invoice.Label"))
            .append("</td>").append("<td colspan=\"2\">").append(nameDoc).append("</td>").append("</tr>")
            .append("<td>").append(DBProperties.getProperty("Sales_DocumentAbstract/RateCrossTotal.Label"))
            .append("</td>").append("<td>").append(rateCross).append(" ").append(tarCurr.getSymbol())
            .append("</td>").append("<td>").append(crossTotal).append(" ").append(curr.getSymbol())
            .append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.newTotal.Label"))
            .append("</td>").append("<td colspan=\"2\" align=\"right\">").append(newCrossTotal).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>");
    if (gainloss.compareTo(BigDecimal.ZERO) == -1) {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.loss.Label"));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.gain.Label"));
    }
    html.append("</td>").append("<td colspan=\"2\" align=\"right\">").append(gainloss.abs()).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionDebit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 0, check).length() > 0) {
        html.append(checkAccounts(accs, 0, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionCredit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 1, check).length() > 0) {
        html.append(checkAccounts(accs, 1, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("</table>");
    return html.toString();
}

From source file:io.bitsquare.gui.util.BSFormatter.java

/**
 * Converts to a coin with max. 4 decimal places. Last place gets rounded.
 * 0.01234 -> 0.0123//from  w  w  w . j  a v a  2s.  c  o m
 * 0.01235 -> 0.0124
 *
 * @param input
 * @return
 */
public Coin parseToCoinWith4Decimals(String input) {
    try {
        return Coin.valueOf(new BigDecimal(parseToCoin(cleanInput(input)).value)
                .setScale(-scale - 1, BigDecimal.ROUND_HALF_UP).setScale(scale + 1).toBigInteger().longValue());
    } catch (Throwable t) {
        if (input != null && input.length() > 0)
            log.warn("Exception at parseToCoinWith4Decimals: " + t.toString());
        return Coin.ZERO;
    }
}

From source file:com.qtplaf.library.util.NumberUtils.java

/**
 * Returns a list of increases to apply.
 * /* ww  w.j a  v  a  2s . co m*/
 * @param integerDigits The number of integer digits.
 * @param decimalDigits The numbeer of decimal digits.
 * @param multipliers The list of multipliers.
 * @return The list of increases.
 */
public static List<BigDecimal> getIncreases(int integerDigits, int decimalDigits, int... multipliers) {
    List<BigDecimal> increaments = new ArrayList<>();
    int upperScale = decimalDigits;
    int lowerScale = (integerDigits - 1) * (-1);
    for (int scale = upperScale; scale >= lowerScale; scale--) {
        for (int multiplier : multipliers) {
            BigDecimal value = NumberUtils.getBigDecimal(Math.pow(10, -scale), scale);
            BigDecimal multiplicand = new BigDecimal(multiplier).setScale(0, BigDecimal.ROUND_HALF_UP);
            increaments.add(value.multiply(multiplicand));
        }
    }
    return increaments;
}

From source file:com.spaceprogram.simplejpa.util.AmazonSimpleDBUtil.java

public static String encodeRealNumberRange(BigDecimal number, int maxDigitsLeft, int maxDigitsRight,
        BigDecimal offsetValue) {
    BigDecimal shiftMultiplier = new BigDecimal(Math.pow(10, maxDigitsRight));
    //        System.out.println("shiftMultiplier=" + shiftMultiplier);
    BigDecimal shiftedNumber = number.multiply(shiftMultiplier);
    //        System.out.println("shiftedNumber=" + shiftedNumber);
    shiftedNumber = shiftedNumber.setScale(0, BigDecimal.ROUND_HALF_UP);
    //        System.out.println("shiftedNumber rounded=" + shiftedNumber);
    BigDecimal shiftedOffset = offsetValue.multiply(shiftMultiplier);
    //        System.out.println("shiftedOffset=" + shiftedOffset);
    BigDecimal offsetNumber = shiftedNumber.add(shiftedOffset);
    //        System.out.println("offsetNumber=" + offsetNumber);
    String longString = offsetNumber.toString();
    //        System.out.println("shifted string=" + longString);
    int numBeforeDecimal = longString.length();
    int numZeroes = maxDigitsLeft + maxDigitsRight - numBeforeDecimal;
    StringBuffer strBuffer = new StringBuffer(numZeroes + longString.length());
    for (int i = 0; i < numZeroes; i++) {
        strBuffer.insert(i, '0');
    }/*  ww w.  j  ava 2s. c om*/
    strBuffer.append(longString);
    return strBuffer.toString();
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on a BigDecimal price, returns the price with tax
 * /*from  w  w w  .  j  a va2s .co  m*/
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public BigDecimal calculateTax(BigDecimal amount, long taxClassId, Customer customer, int merchantId)
        throws Exception {

    // no tax calculation id taxClassId==-1
    if (taxClassId == -1) {
        return amount;
    }

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    ConfigurationRequest request = new ConfigurationRequest(merchantId, ShippingConstants.MODULE_TAX_BASIS);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    Collection taxCollection = null;
    if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {
        taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                customer.getCustomerZoneId(), taxClassId, merchantId);
    } else {
        taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                customer.getCustomerBillingZoneId(), taxClassId, merchantId);
    }

    BigDecimal currentAmount = new BigDecimal(0);
    currentAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    if (taxCollection != null) {

        Iterator i = taxCollection.iterator();
        while (i.hasNext()) {

            TaxRate trv = (TaxRate) i.next();
            BigDecimal amountForCalculation = amount;
            if (trv.isPiggyback()) {
                amountForCalculation = amountForCalculation.add(currentAmount);
            }

            double value = ((trv.getTaxRate().doubleValue() * amountForCalculation.doubleValue()) / 100)
                    + amountForCalculation.doubleValue();
            currentAmount = currentAmount.add(new BigDecimal(value));

        }

    }

    return currentAmount;

}

From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * /*from   w w  w. j  a  va 2 s  .  com*/
 * @param accountTransaction
 * @param user
 * @throws java.lang.Exception
 */
public synchronized void commitTransaction(Transaction accountTransaction, User user) throws Exception {
    if (!enableAccounting) {
        return;
    }

    if (accountTransaction != null) {
        //Create an EntityManager
        log.debug("Getting entity manager ......");
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
        //Get the account and set the current balance. Update the class variable at the same time.
        Account account = (Account) em.find(Account.class, organizationId);
        balance = account.getCreditBalance();
        //Set the account & user for the accountTransaction.
        accountTransaction.setAccount(account);
        accountTransaction.setUser(user);

        try {
            //Run validation (checks what type of transaction is allowed..)
            accountTransaction.validate();

            //Now check if the transaction either has to deposit or withdraw...
            BigDecimal newBalance = null;
            if (accountTransaction.getType() == Transaction.DEPOSIT) {
                newBalance = balance.add(accountTransaction.getCreditAlteration());
            } else if (accountTransaction.getType() == Transaction.WITHDRAW) {
                newBalance = balance.subtract(accountTransaction.getCreditAlteration());
                if (newBalance.doubleValue() < 0) {
                    throw new TransactionDeniedException("Insufficient credits for transaction. "
                            + "Required credits: "
                            + accountTransaction.getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP)
                                    .toString()
                            + ", " + "Current balance: "
                            + balance.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }
            } else {
                log.error("Unsupported transaction type");
                throw new Exception("Unsupported transaction type");
            }

            account.setCreditBalance(newBalance);
            accountTransaction.setMutationDate(new Date());
            accountTransaction.setStatus(Transaction.ACCEPTED);

            Iterator iterPriceComp = accountTransaction.getLayerPriceCompositions().iterator();
            while (iterPriceComp.hasNext()) {
                LayerPriceComposition lpc = (LayerPriceComposition) iterPriceComp.next();
                em.persist(lpc);
            }

            em.merge(accountTransaction);
            em.flush();
            balance = newBalance;
        } catch (TransactionDeniedException tde) {
            accountTransaction.setErrorMessage(tde.getMessage());
            accountTransaction.setStatus(Transaction.REFUSED);
            em.merge(accountTransaction);
            em.flush();
            throw tde;
        }
    }
}

From source file:com.brq.wallet.lt.activity.TraderInfoFragment.java

private static Double roundDoubleHalfUp(double value, int decimals) {
    return BigDecimal.valueOf(value).setScale(decimals, BigDecimal.ROUND_HALF_UP).doubleValue();
}

From source file:org.apache.rocketmq.tools.command.cluster.CLusterSendMsgRTCommand.java

@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
    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 av  a2 s. c om
        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')
                && 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.printf("%s",
                                String.format("%s|%s|%s|%s|%s%n", getCurTime(), machineRoom, clusterName,
                                        brokerName, new BigDecimal(rt).setScale(0, BigDecimal.ROUND_HALF_UP)));
                    }

                }

            }

            Thread.sleep(interval * 1000);
        }

    } catch (Exception e) {
        throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
    } finally {
        defaultMQAdminExt.shutdown();
        producer.shutdown();
    }
}