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.sakaiproject.profile2.job.KudosJob.java

/**
 * Gets the score as a percentage, two decimal precision
 * @param score      score for user/*from   www .  j  av  a2  s. c om*/
 * @param total      total possible score
 * @return
 */
private BigDecimal getScoreAsPercentage(BigDecimal score, BigDecimal total) {
    return score.divide(total, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100")).stripTrailingZeros();
}

From source file:org.openbravo.erpCommon.utility.CashVATUtil.java

/**
 * Generic method to calculate the percentage of an amount (totalAmt) with the currency's standard
 * precision//  w  w w  .  j a va2 s .c  om
 * 
 * @param percentage
 *          percentage to apply for the totalAmt
 * @param totalAmt
 *          total amount (represents 100%)
 * @param currency
 *          currency
 * @return percentage * totalAmt / 100, rounded to the currency's standard precision
 */
public static BigDecimal calculatePercentageAmount(final BigDecimal percentage, final BigDecimal totalAmt,
        final Currency currency) {
    try {
        OBContext.setAdminMode(true);
        if (currency != null) {
            int precission = currency.getStandardPrecision().intValue();
            return percentage.multiply(totalAmt).divide(_100, precission, RoundingMode.HALF_UP);
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    throw new RuntimeException("CashVATUtil.calculatePercentageAmount(), wrong parameters :" + percentage + ", "
            + totalAmt + ", " + currency);
}

From source file:org.openconcerto.erp.core.supplychain.receipt.component.BonReceptionSQLComponent.java

private void updateTotal() {
    RowValuesTableModel model = this.tableBonItem.getModel();

    long totalHT = 0;
    long totalTTC = 0;
    int columnIndexHT = model.getColumnIndexForElement(this.tableBonItem.getPrixTotalHTElement());
    int columnIndexTTC = model.getColumnIndexForElement(this.tableBonItem.getPrixTotalTTCElement());

    // columnIndexHT = model.getColumnIndexForElement(getTable().get);
    for (int i = 0; i < model.getRowCount(); i++) {
        BigDecimal nHT = (BigDecimal) model.getValueAt(i, columnIndexHT);
        totalHT += nHT.movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
        BigDecimal nTTC = (BigDecimal) model.getValueAt(i, columnIndexTTC);
        totalTTC += nTTC.movePointRight(2).setScale(0, RoundingMode.HALF_UP).longValue();
    }//w w w  .j ava2  s. co m

    this.textTotalHT.setText(GestionDevise.currencyToString(totalHT));
    this.textTotalTVA.setText(GestionDevise.currencyToString(totalTTC - totalHT));
    this.textTotalTTC.setText(GestionDevise.currencyToString(totalTTC));
}

From source file:jp.furplag.util.commons.NumberUtils.java

/**
 * generate cosine factor for trigonometric functions in BigDecimal.
 *
 * @param mc {@link java.math.MathContext}.
 * @return list of cosine factors.//from  w w  w  .  ja v  a2s.  c om
 */
private static List<BigDecimal> initCosineFactor(MathContext mc) {
    int precision = (mc == null ? MathContext.DECIMAL128 : mc).getPrecision();
    List<BigDecimal> factors = new ArrayList<BigDecimal>();
    BigDecimal divisor = BigDecimal.valueOf(2d);
    BigDecimal temporary = BigDecimal.valueOf(2d);
    do {
        factors.add(BigDecimal.ONE.divide(divisor, precision + 2, RoundingMode.HALF_UP));
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
        temporary = temporary.add(BigDecimal.ONE);
        divisor = divisor.multiply(temporary);
    } while (factors.get(factors.size() - 1).compareTo(new BigDecimal("1E-" + (precision + 2))) > 0);

    return factors;
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

private void setAutoAmplitude(double value) {
    int val = new BigDecimal(value * 100).divide(BigDecimal.ONE, 0, RoundingMode.HALF_UP).intValue();
    if (amplitude.getValue() == value)
        return;//from  w w w  .j  ava 2 s .c  om
    isEntrainerAmplitudeMessage = true;
    amplitude.setValue(val);
}

From source file:org.kuali.ole.select.document.service.impl.OlePaymentRequestServiceImpl.java

/**
 * @see org.kuali.ole.select.document.service.OlePaymentRequestService#calculateProrateItemSurcharge(org.kuali.ole.select.document.OlePaymentRequestDocument)
 *///  w ww  .j a va  2 s.com
@Override
public void calculateProrateItemSurcharge(OlePaymentRequestDocument paymentRequestDocument) {
    LOG.debug("Inside Calculation for ProrateItemSurcharge");
    //  KualiDecimal addChargeItem = paymentRequestDocument.getGrandPreTaxTotalExcludingDiscount().subtract(paymentRequestDocument.getLineItemPreTaxTotal());
    BigDecimal addChargeItem = BigDecimal.ZERO;
    List<OlePaymentRequestItem> item = paymentRequestDocument.getItems();

    for (OlePaymentRequestItem items : item) {
        if (!items.getItemType().isQuantityBasedGeneralLedgerIndicator()
                && !items.getItemTypeCode()
                        .equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_PMT_TERMS_DISCOUNT_CODE)
                && items.getItemUnitPrice() != null) {
            addChargeItem = addChargeItem.add(items.getItemUnitPrice());
        }
    }
    List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>();
    BigDecimal totalExtPrice = new BigDecimal(0);
    BigDecimal newUnitPrice = new BigDecimal(0);
    BigDecimal extPrice = new BigDecimal(0);
    BigDecimal unitPricePercent = new BigDecimal(0);
    BigDecimal hundred = new BigDecimal(100);
    BigDecimal one = new BigDecimal(1);
    BigDecimal totalSurCharge = new BigDecimal(0);
    BigDecimal totalItemQuantity = new BigDecimal(0);
    BigDecimal itemSurchargeCons = new BigDecimal(0);
    for (int i = 0; item.size() > i; i++) {
        OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i);
        if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                totalItemQuantity = totalItemQuantity.add(items.getItemQuantity().bigDecimalValue());
            }
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
                    || paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    || paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                if (items.getItemDiscount() == null) {
                    items.setItemDiscount(KualiDecimal.ZERO);
                }
                if (items.getItemDiscountType() != null && items.getItemDiscountType()
                        .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
                    newUnitPrice = (hundred.subtract(items.getItemDiscount().bigDecimalValue())).divide(hundred)
                            .multiply(items.getItemListPrice().bigDecimalValue());
                } else {
                    newUnitPrice = items.getItemListPrice().bigDecimalValue()
                            .subtract(items.getItemDiscount().bigDecimalValue());
                }
                newUnitPriceList.add(newUnitPrice);
                extPrice = newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue());
                totalExtPrice = totalExtPrice.add(extPrice);
            }
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
                if (items.getItemSurcharge() == null) {
                    items.setItemSurcharge(BigDecimal.ZERO);
                }
                totalSurCharge = totalSurCharge
                        .add(items.getItemQuantity().bigDecimalValue().multiply(items.getItemSurcharge()));
            }
        }

    }
    if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
        if (totalItemQuantity.compareTo(BigDecimal.ZERO) != 0) {
            itemSurchargeCons = one.divide(totalItemQuantity, 8, RoundingMode.HALF_UP);
        }
    }
    for (int i = 0, j = 0; item.size() > i; i++) {
        OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i);
        if (items.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) {
                if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) {
                    unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8, RoundingMode.HALF_UP);
                }
                items.setItemSurcharge(
                        unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge()));
            }
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                items.setItemSurcharge(
                        itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge()));
            }
            if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    && items.getItemSurcharge() != null) {
                items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge()));
            }
            j++;
        }
    }
    if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
        if (totalSurCharge.compareTo(addChargeItem) != 0) {
            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
                    OLEKeyConstants.ERROR_PAYMENT_REQUEST_TOTAL_MISMATCH);
        }
    }
    LOG.debug("Leaving Calculation for ProrateItemSurcharge");
}

From source file:net.sourceforge.entrainer.gui.socket.EntrainerSocketConnector.java

private void setAutoPinkNoise(double value) {
    int val = new BigDecimal(value * 1000).divide(BigDecimal.ONE, 0, RoundingMode.HALF_UP).intValue();
    if (pinkNoise.getValue() == val)
        return;//from   w  ww  .  j  a v a2 s. co  m
    isEntrainerPinkNoiseAmplitudeMessage = true;
    pinkNoise.setValue(val);
}

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

/**
 * {@inheritDoc}/*from   w w w  .j av  a2  s.  c o m*/
 */
public Payment refund(final Payment payment) {
    final Logger log = ShopCodeContext.getLog(this);
    if (log.isDebugEnabled()) {
        log.debug("Credit on prev auth " + payment);
    }

    final HashMap<String, String> request = new HashMap<String, String>();

    request.put("ccCreditService_run", "true");

    request.put("ccCreditService_captureRequestID", payment.getTransactionAuthorizationCode());
    request.put("ccCreditService_captureRequestToken", payment.getTransactionRequestToken());

    request.put("purchaseTotals_currency", payment.getOrderCurrency());
    request.put("purchaseTotals_grandTotalAmount",
            payment.getPaymentAmount().setScale(2, RoundingMode.HALF_UP).toString());

    request.put("merchantID", (String) getProperties().get(CS_MERCHANT_ID));
    request.put("requestID", payment.getTransactionAuthorizationCode());
    request.put("requestToken", payment.getTransactionRequestToken());
    request.put("merchantReferenceCode", payment.getTransactionReferenceId());

    return runTransaction(request, payment, REFUND);
}

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

@Override
@Transactional(rollbackFor = { NoEstaAbiertaException.class, ProductoNoSoportaFraccionException.class })
public LoteEntrada creaLote(LoteEntrada lote)
        throws ProductoNoSoportaFraccionException, NoEstaAbiertaException {
    log.debug("Creando lote {}", lote);
    lote.setProducto((Producto) currentSession().get(Producto.class, lote.getProducto().getId()));
    lote.setEntrada((Entrada) currentSession().get(Entrada.class, lote.getEntrada().getId()));
    if (lote.getEntrada().getEstatus().getNombre().equals(Constantes.ABIERTA)) {
        if (!lote.getProducto().getFraccion()) {
            BigDecimal[] resultado = lote.getCantidad().divideAndRemainder(new BigDecimal("1"));
            if (resultado[1].doubleValue() > 0) {
                throw new ProductoNoSoportaFraccionException();
            }/*from w  w  w.ja  v a 2s  . com*/
        }

        BigDecimal subtotal = lote.getPrecioUnitario().multiply(lote.getCantidad());
        BigDecimal iva = subtotal.multiply(lote.getProducto().getIva()).setScale(2, RoundingMode.HALF_UP);
        lote.setIva(iva);
        lote.setFechaCreacion(new Date());

        currentSession().save(lote);

        return lote;
    } else {
        throw new NoEstaAbiertaException("No se puede crear un lote en una entrada que no este abierta");
    }
}

From source file:org.openbravo.common.actionhandler.SetNewBPCurrency.java

private BigDecimal getConversionRate(String strOrgId, String strFromCurrencyId, String strToCurrencyId) {
    final Date today = new Date();
    BigDecimal exchangeRate = BigDecimal.ZERO;
    // Apply default conversion rate
    int conversionRatePrecision = FIN_Utility
            .getConversionRatePrecision(RequestContext.get().getVariablesSecureApp());
    Organization organization = OBDal.getInstance().get(Organization.class, strOrgId);
    Currency fromCurrency = OBDal.getInstance().get(Currency.class, strFromCurrencyId);
    Currency toCurrency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
    final ConversionRate conversionRate = FIN_Utility.getConversionRate(fromCurrency, toCurrency, today,
            organization);// w  w w  . ja  va  2  s  .c  o m
    if (conversionRate != null) {
        exchangeRate = conversionRate.getMultipleRateBy().setScale(conversionRatePrecision,
                RoundingMode.HALF_UP);
    } else {
        exchangeRate = BigDecimal.ZERO;
    }
    return exchangeRate;
}