Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode 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:org.renjin.primitives.MathGroup.java

@Deferrable
@Builtin/*from  w  ww .  j ava  2s.c o m*/
@DataParallel(value = PreserveAttributeStyle.ALL, passNA = true)
public static double signif(double x, int digits) {
    if (Double.isInfinite(x) || Double.isNaN(x)) {
        return x;
    }
    if (digits <= 0) {
        digits = 1;
    }
    return new BigDecimal(x).round(new MathContext(digits, RoundingMode.HALF_UP)).doubleValue();
}

From source file:com.ar.dev.tierra.api.dao.impl.FiscalDAOImpl.java

@Override
public void factura_b(List<DetalleFactura> detalles, Cliente cliente) {
    try (PrintWriter ticket = new PrintWriter("command/factura_b.200")) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(1);
        ticket.println("b" + (char) 28 + cliente.getNombreCliente() + (char) 28 + cliente.getDocumento()
                + (char) 28 + cliente.getResponsabilidadIva() + (char) 28 + cliente.getTipoDocumento()
                + (char) 28 + cliente.getDomicilio());
        ticket.println("@" + (char) 28 + "B" + (char) 28 + "T");
        BigDecimal descuento = new BigDecimal(BigInteger.ZERO);
        for (DetalleFactura detalle : detalles) {
            if (detalle.getDescuentoDetalle() != null) {
                descuento = descuento.add(detalle.getDescuentoDetalle());
            }/*ww w. j  a  va  2 s  .c o m*/
            String price = null;
            BigDecimal sinIVA = detalle.getProducto().getPrecioVenta().subtract(detalle.getProducto()
                    .getPrecioVenta().multiply(new BigDecimal(17.35)).divide(new BigDecimal(100)));
            price = sinIVA.setScale(4, RoundingMode.HALF_UP).toString();
            ticket.println("B" + (char) 28 /*Abrimos linea*/
                    + detalle.getProducto().getDescripcion() + (char) 28 /*Nombre producto*/
                    + detalle.getCantidadDetalle() + ".0" + (char) 28 /*Cantidad*/
                    + price.replace(",", ".") + (char) 28 /*Precio unitario*/
                    + "21.0" + (char) 28 /*Impuestos IVA*/
                    + "M" + (char) 28 /*Suma monto*/
                    + "0.0" + (char) 28 /*Impuestos internos*/
                    + "0" + (char) 28 /*Parametro display*/
                    + "b");
            /*Cierra de linea*/
        }
        if (!descuento.equals(new BigDecimal(BigInteger.ZERO))) {
            ticket.println("T" + (char) 28 /*Abrimos linea descuento*/
                    + "Descuento: " + (char) 28 /*Texto a mostrar*/
                    + descuento + (char) 28 /*Monto descuento*/
                    + "m" + (char) 28 /*m: descuento, M: aumento*/
                    + "0" + (char) 28 /*parametro display*/
                    + "T");
            /*cierre linea descuento*/
        }
        ticket.println("E");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FiscalDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

/**
 * {@inheritDoc}/*from   w ww .  ja v  a2 s .co m*/
 */
public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount,
        final String currencyCode, final String orderGuid, final Payment payment) {

    final LiqPay api = getLiqPayAPI();

    final HashMap<String, String> params = new LinkedHashMap<String, String>();
    params.put("amount", amount.setScale(2, RoundingMode.HALF_UP).toPlainString());
    params.put("server_url", getParameterValue(LP_SERVER_URL));
    params.put("description", getDescription(payment));
    params.put("pay_way", getParameterValue(LP_PAYWAY_URL));
    params.put("result_url", getParameterValue(LP_RESULT_URL));

    params.put("type", "buy");
    params.put("order_id", orderGuid);

    params.put("currency", currencyCode);
    params.put("formDataOnly", "formDataOnly"); // YC specific

    return api.cnb_form(params);

}

From source file:universal.Calc.java

public static BigDecimal sqrt(BigDecimal A, final int SCALE) {
    BigDecimal x0 = new BigDecimal("0");
    BigDecimal x1 = new BigDecimal(Math.sqrt(A.doubleValue()));
    while (!x0.equals(x1)) {
        x0 = x1;/*  www.  j  a  va 2s .  c  om*/
        x1 = A.divide(x0, SCALE, RoundingMode.HALF_UP);
        x1 = x1.add(x0);
        x1 = x1.divide(new BigDecimal(2), SCALE, RoundingMode.HALF_UP);
    }
    return x1;
}

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

/**
 * Gets the JS 4 fit exchange rate.//from  w  w  w  .j  a v  a2s  .  co  m
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _parameterClone the parameter clone
 * @return the JS 4 fit ex rate
 * @throws EFapsException on error
 */
protected StringBuilder getJS4FitExRate(final Parameter _parameter, final Parameter _parameterClone)
        throws EFapsException {
    final StringBuilder ret = new StringBuilder();
    try {
        String postfix = null;
        boolean eval = true;
        while (eval) {
            eval = postfix == null;
            postfix = postfix == null ? "Debit" : "Credit";
            final String[] selected = _parameter.getParameterValues("posSelect_" + postfix);
            if (ArrayUtils.isNotEmpty(selected)) {
                for (int i = 0; i < selected.length; i++) {
                    if (BooleanUtils.toBoolean(selected[i])) {
                        eval = false;
                        final DecimalFormat formater = NumberFormatter.get().getTwoDigitsFormatter();

                        final Instance periodInst = new Period().evaluateCurrentPeriod(_parameterClone);
                        final Instance periodCurrenycInstance = new Period().getCurrency(periodInst)
                                .getInstance();

                        final BigDecimal sumDebit = getSum4UI(_parameter, "Debit", null, null);
                        final BigDecimal sumCredit = getSum4UI(_parameter, "Credit", null, null);
                        final BigDecimal diff = "Debit".equals(postfix) ? sumCredit.subtract(sumDebit)
                                : sumDebit.subtract(sumCredit);

                        final String currAmountStr = _parameter.getParameterValues("amount_" + postfix)[i];
                        final BigDecimal currAmount = StringUtils.isEmpty(currAmountStr) ? BigDecimal.ZERO
                                : (BigDecimal) formater.parse(currAmountStr);

                        final RateInfo rateInfo = getRateInfo4UI(_parameterClone, "_" + postfix, i);

                        final BigDecimal currAmountRate = Currency.convertToCurrency(_parameter, currAmount,
                                rateInfo, null, periodCurrenycInstance).setScale(2, RoundingMode.HALF_UP);

                        final BigDecimal targetRate = currAmountRate.add(diff);

                        if (BigDecimal.ZERO.compareTo(targetRate) < 0
                                && BigDecimal.ZERO.compareTo(currAmount) < 0) {
                            final BigDecimal rate;
                            if (rateInfo.isInvert()) {
                                rate = targetRate.setScale(8, RoundingMode.HALF_UP).divide(currAmount,
                                        RoundingMode.HALF_UP);
                            } else {
                                rate = currAmount.setScale(8, RoundingMode.HALF_UP).divide(targetRate,
                                        RoundingMode.HALF_UP);
                            }

                            final String rateStr = NumberFormatter.get().getFormatter(null, 8).format(rate);
                            final String amountRateStr = formater.format(targetRate);

                            ret.append(getSetFieldValue(i, "amountRate_" + postfix, amountRateStr))
                                    .append(getSetFieldValue(i, "rate_" + postfix, rateStr));
                            ParameterUtil.setParameterValue(_parameterClone, "amountRate_" + postfix, i,
                                    amountRateStr);
                            ParameterUtil.setParameterValue(_parameterClone, "rate_" + postfix, i, rateStr);

                            final BigDecimal sumDebit2 = getSum4UI(_parameterClone, "Debit", null, null);
                            final BigDecimal sumCredit2 = getSum4UI(_parameterClone, "Credit", null, null);

                            final String sumDebitStr = formater.format(sumDebit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumCreditStr = formater.format(sumCredit2) + " "
                                    + new Period().getCurrency(periodInst).getSymbol();
                            final String sumTotalStr = formater.format(sumDebit2.subtract(sumCredit2).abs())
                                    + " " + new Period().getCurrency(periodInst).getSymbol();

                            ret.append(getSetFieldValue(0, "sumDebit", sumDebitStr))
                                    .append(getSetFieldValue(0, "sumCredit", sumCreditStr))
                                    .append(getSetFieldValue(0, "sumTotal", sumTotalStr));
                            break;
                        }
                    }
                }
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "update4Currency.ParseException", e);
    }
    return ret;
}

From source file:net.sourceforge.subsonic.backend.controller.MultiController.java

public ModelAndView payment(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!authenticate(request, response)) {
        return null;
    }/*from ww w.  j av  a  2s.co  m*/

    int days = ServletRequestUtils.getIntParameter(request, "days", 30);

    SortedMap<Date, Money> payments = new TreeMap<Date, Money>();

    Calendar startOfDay = Calendar.getInstance();
    startOfDay.set(Calendar.HOUR_OF_DAY, 0);
    startOfDay.set(Calendar.MINUTE, 0);
    startOfDay.set(Calendar.SECOND, 0);
    startOfDay.set(Calendar.MILLISECOND, 0);

    Calendar endOfDay = Calendar.getInstance();
    endOfDay.setTime(startOfDay.getTime());
    endOfDay.add(Calendar.DATE, 1);

    for (int i = 0; i < days; i++) {
        payments.put(startOfDay.getTime(),
                getAmountForPeriod(CurrencyUnit.EUR, startOfDay.getTime(), endOfDay.getTime()));
        startOfDay.add(Calendar.DATE, -1);
        endOfDay.add(Calendar.DATE, -1);
    }

    Money sum = computeSum(payments.values());
    Money average = sum.dividedBy(days, RoundingMode.HALF_UP);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("payments", payments);
    map.put("sum", sum);
    map.put("average", average);

    return new ModelAndView("backend/payment", "model", map);
}

From source file:org.projectforge.business.fibu.kost.BuchungssatzDO.java

public void setBetrag(final BigDecimal betrag) {
    this.betrag = betrag != null ? betrag.setScale(2, RoundingMode.HALF_UP) : null;
}

From source file:org.kuali.coeus.common.budget.impl.personnel.BudgetPersonnelBudgetServiceImpl.java

public List<BudgetPersonSalaryDetails> calculatePersonSalary(Budget budget, int personIndex) {

    List<BudgetPersonSalaryDetails> budgetPersonSalaryDetails = new ArrayList<BudgetPersonSalaryDetails>();
    String rate = getParameterService().getParameterValueAsString(ProposalDevelopmentDocument.class,
            Constants.DEFAULT_INFLATION_RATE_FOR_SALARY);
    List<BudgetPeriod> budgetPeriodList = null;
    BigDecimal actualPersonSalary = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal personSalary = ScaleTwoDecimal.ZERO.bigDecimalValue();
    BigDecimal newRate = new ScaleTwoDecimal(rate).bigDecimalValue();
    budgetPeriodList = budget.getBudgetPeriods();

    BudgetPerson budgetPerson = budget.getBudgetPerson(personIndex);
    for (BudgetPeriod budgetPeriodData : budgetPeriodList) {
        BudgetPersonSalaryDetails personSalaryDetails = new BudgetPersonSalaryDetails();

        personSalaryDetails.setBudgetPerson(budgetPerson);
        personSalaryDetails.setBudgetId(budget.getBudgetId());
        personSalaryDetails.setPersonSequenceNumber(budgetPerson.getPersonSequenceNumber());
        personSalaryDetails.setBudgetPeriod(budgetPeriodData.getBudgetPeriod());
        personSalaryDetails.setPersonId(budgetPerson.getPersonId());
        if (budgetPeriodData.getBudgetPeriod() == BUDGET_PERIOD_1) {
            if (budgetPerson.getEffectiveDate().equals(budgetPerson.getStartDate())) {

                personSalaryDetails.setBaseSalary(budgetPerson.getCalculationBase());
                actualPersonSalary = budgetPerson.getCalculationBase().bigDecimalValue();

            } else {

                actualPersonSalary = budgetPerson
                        .getCalculationBase().add(new ScaleTwoDecimal(budgetPerson.getCalculationBase()
                                .bigDecimalValue().multiply(newRate.divide(
                                        new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP))))
                        .bigDecimalValue();

            }//w w w.ja  va  2 s .  com

        } else {

            personSalary = actualPersonSalary.add(actualPersonSalary.multiply(
                    newRate.divide(new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP)));
            personSalaryDetails.setBaseSalary(new ScaleTwoDecimal(personSalary));
            actualPersonSalary = personSalary;
        }
        budgetPersonSalaryDetails.add(personSalaryDetails);
    }
    return budgetPersonSalaryDetails;
}

From source file:org.libreplan.web.montecarlo.MonteCarloModel.java

@Override
public Map<LocalDate, BigDecimal> calculateMonteCarlo(List<MonteCarloTask> tasks, int iterations,
        IDesktopUpdatesEmitter<Integer> iterationProgress) {

    MonteCarloCalculation monteCarloCalculation = new MonteCarloCalculation(copyOf(tasks), iterations,
            iterationProgress);/*  ww w.j av a  2s.  c om*/
    Map<LocalDate, BigDecimal> monteCarloValues = monteCarloCalculation.doCalculation();

    // Convert number of times to probability
    for (LocalDate key : monteCarloValues.keySet()) {
        BigDecimal times = monteCarloValues.get(key);
        BigDecimal probability = times.divide(BigDecimal.valueOf(iterations), 8, RoundingMode.HALF_UP);
        monteCarloValues.put(key, probability);
    }

    return monteCarloValues;
}

From source file:org.thymeleaf.util.EvaluationUtilTest.java

@Test
public void convertToNumberTest() {

    Assert.assertEquals(null, EvaluationUtil.evaluateAsNumber(null));

    Assert.assertEquals(BigDecimal.valueOf(23.0f), EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(23.0f)));
    Assert.assertEquals(BigDecimal.valueOf(23.89754f),
            EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(23.89754f)));
    Assert.assertEquals(BigDecimal.valueOf(23.89754d),
            EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(23.89754d)));
    Assert.assertEquals(BigDecimal.ZERO, EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(0)));
    Assert.assertEquals(BigDecimal.valueOf(0.0d), EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(0.0d)));
    Assert.assertNotEquals(BigDecimal.valueOf(23.1f),
            EvaluationUtil.evaluateAsNumber(BigDecimal.valueOf(23.0f)));

    Assert.assertEquals(BigDecimal.valueOf(23), EvaluationUtil.evaluateAsNumber(BigInteger.valueOf(23)));
    Assert.assertEquals(BigDecimal.valueOf(0), EvaluationUtil.evaluateAsNumber(BigInteger.valueOf(0)));
    Assert.assertEquals(BigDecimal.valueOf(-2323232),
            EvaluationUtil.evaluateAsNumber(BigInteger.valueOf(-2323232)));

    Assert.assertEquals(BigDecimal.valueOf(-232), EvaluationUtil.evaluateAsNumber(Short.valueOf("-232")));
    Assert.assertEquals(BigDecimal.valueOf(232), EvaluationUtil.evaluateAsNumber(Short.valueOf("232")));
    Assert.assertEquals(BigDecimal.valueOf(0), EvaluationUtil.evaluateAsNumber(Short.valueOf("0")));

    Assert.assertEquals(BigDecimal.valueOf(-232232),
            EvaluationUtil.evaluateAsNumber(Integer.valueOf("-232232")));
    Assert.assertEquals(BigDecimal.valueOf(232232), EvaluationUtil.evaluateAsNumber(Integer.valueOf("232232")));
    Assert.assertEquals(BigDecimal.valueOf(0), EvaluationUtil.evaluateAsNumber(Integer.valueOf("0")));

    Assert.assertEquals(BigDecimal.valueOf(-23223212121L),
            EvaluationUtil.evaluateAsNumber(Long.valueOf("-23223212121")));
    Assert.assertEquals(BigDecimal.valueOf(23223212121L),
            EvaluationUtil.evaluateAsNumber(Long.valueOf("23223212121")));
    Assert.assertEquals(BigDecimal.valueOf(0), EvaluationUtil.evaluateAsNumber(Long.valueOf("0")));

    Assert.assertTrue(/*from w  w  w.  j ava2s  .  co  m*/
            BigDecimal.valueOf(23.0f).compareTo(EvaluationUtil.evaluateAsNumber(Float.valueOf(23.0f))) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.89754f);
        num = num.setScale(5, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber(Float.valueOf(23.89754f));
        result = result.setScale(5, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) == 0);
    }
    Assert.assertTrue(BigDecimal.ZERO.compareTo(EvaluationUtil.evaluateAsNumber(Float.valueOf(0))) == 0);
    Assert.assertTrue(
            BigDecimal.valueOf(0.0d).compareTo(EvaluationUtil.evaluateAsNumber(Float.valueOf(0.0f))) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.1f);
        num = num.setScale(1, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber(Float.valueOf(23.0f));
        result = result.setScale(1, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) != 0);
    }

    Assert.assertTrue(
            BigDecimal.valueOf(23.0d).compareTo(EvaluationUtil.evaluateAsNumber(Double.valueOf(23.0d))) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.89754d);
        num = num.setScale(5, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber(Double.valueOf(23.89754d));
        result = result.setScale(5, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) == 0);
    }
    Assert.assertTrue(BigDecimal.ZERO.compareTo(EvaluationUtil.evaluateAsNumber(Double.valueOf(0))) == 0);
    Assert.assertTrue(
            BigDecimal.valueOf(0.0d).compareTo(EvaluationUtil.evaluateAsNumber(Double.valueOf(0.0d))) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.1d);
        num = num.setScale(1, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber(Double.valueOf(23.0d));
        result = result.setScale(1, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) != 0);
    }

    Assert.assertTrue(BigDecimal.valueOf(23.0d).compareTo(EvaluationUtil.evaluateAsNumber("23.0")) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.89754d);
        num = num.setScale(5, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber("23.89754");
        result = result.setScale(5, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) == 0);
    }
    Assert.assertTrue(BigDecimal.ZERO.compareTo(EvaluationUtil.evaluateAsNumber("0")) == 0);
    Assert.assertTrue(BigDecimal.valueOf(0.0d).compareTo(EvaluationUtil.evaluateAsNumber("0.0")) == 0);
    {
        BigDecimal num = BigDecimal.valueOf(23.1d);
        num = num.setScale(1, RoundingMode.HALF_UP);
        BigDecimal result = EvaluationUtil.evaluateAsNumber("23.0");
        result = result.setScale(1, RoundingMode.HALF_UP);
        Assert.assertTrue(num.compareTo(result) != 0);
    }

    Assert.assertNull(EvaluationUtil.evaluateAsNumber("something"));
    Assert.assertNull(EvaluationUtil.evaluateAsNumber(EvaluationUtil.class));

}