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.yes.cart.payment.impl.CyberSourcePaymentGatewayImpl.java

/**
 * {@inheritDoc}//  w  w  w. j  a  va  2s  .  c  o m
 */
public Payment authorize(final Payment payment) {
    final Logger log = ShopCodeContext.getLog(this);
    if (log.isDebugEnabled()) {
        log.debug("Authorize " + payment);
    }

    final HashMap<String, String> request = new HashMap<String, String>();
    request.put("ccAuthService_run", "true");
    request.put("businessRules_ignoreAVSResult", "true"); //CP
    request.put("merchantReferenceCode",
            StringUtils.isBlank(payment.getTransactionReferenceId()) ? UUID.randomUUID().toString()
                    : payment.getTransactionReferenceId());

    request.put("billTo_email", payment.getBillingEmail());

    addAddress(request, "billTo_", payment.getBillingAddress());
    addAddress(request, "shipTo_", payment.getShippingAddress());

    if (CARD_LABEL_CODE_MAP.get(payment.getCardType()) != null) {
        request.put("card_cardType", CARD_LABEL_CODE_MAP.get(payment.getCardType()));
    }

    request.put("card_accountNumber", payment.getCardNumber());
    request.put("card_expirationYear", payment.getCardExpireYear());
    request.put("card_expirationMonth", payment.getCardExpireMonth());
    if (payment.getCardCvv2Code() != null) {
        request.put("card_cvNumber", payment.getCardCvv2Code());
    }

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

    if (payment.getOrderItems() != null) {
        for (int index = 0; index < payment.getOrderItems().size(); index++) {
            final PaymentLine paymentLine = payment.getOrderItems().get(index);
            request.put("item_" + index + "_productName", paymentLine.getSkuName());
            request.put("item_" + index + "_productSKU", paymentLine.getSkuCode());
            request.put("item_" + index + "_unitPrice",
                    paymentLine.getUnitPrice().setScale(2, RoundingMode.HALF_UP).toString());
            if (paymentLine.getTaxAmount() != null) {
                request.put("item_" + index + "_taxAmount",
                        paymentLine.getTaxAmount().setScale(2, RoundingMode.HALF_UP).toString());
            }
        }
    }

    return runTransaction(request, payment, AUTH);
}

From source file:org.libreplan.business.workingday.IntraDayDate.java

private EffortDuration calculateProportionalDuration(ResourcesPerDay resourcesPerDay, EffortDuration effort) {
    int seconds = effort.getSeconds();
    BigDecimal end = new BigDecimal(seconds).divide(resourcesPerDay.getAmount(), RoundingMode.HALF_UP);
    return seconds(end.intValue());
}

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

/**
 * Calculate the sum for one of the tables.
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @param _postFix postfix for the field names
 * @param _pos position/*from  www.  jav a2  s .c o m*/
 * @param _rateInfo the _rate info
 * @return sum for the table
 * @throws EFapsException on error
 */
protected BigDecimal getSum4UI(final Parameter _parameter, final String _postFix, final Integer _pos,
        final RateInfo _rateInfo) throws EFapsException {
    final Instance periodInst = new Period().evaluateCurrentPeriod(_parameter);
    final Instance periodCurrenycInstance = new Period().getCurrency(periodInst).getInstance();
    BigDecimal ret = BigDecimal.ZERO;
    try {
        final DecimalFormat formater = NumberFormatter.get().getFormatter(null, null);
        final String[] amounts = _parameter.getParameterValues("amount_" + _postFix);
        if (amounts != null) {
            for (int i = 0; i < amounts.length; i++) {
                final RateInfo rateInfo = _pos != null && i == _pos && _rateInfo != null ? _rateInfo
                        : getRateInfo4UI(_parameter, "_" + _postFix, i);
                final BigDecimal rateAmount = amounts[i] != null && !amounts[i].isEmpty()
                        ? ((BigDecimal) formater.parse(amounts[i])).setScale(8, RoundingMode.HALF_UP)
                        : BigDecimal.ZERO;
                final BigDecimal amount = Currency
                        .convertToCurrency(_parameter, rateAmount, rateInfo, null, periodCurrenycInstance)
                        .setScale(2, RoundingMode.HALF_UP);
                ret = ret.add(amount);
            }
        }
    } catch (final ParseException e) {
        throw new EFapsException(Transaction_Base.class, "getSum.ParseException", e);
    }
    return ret;
}

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

public void calculateProrateItemSurcharge(OleVendorCreditMemoDocument vendorCreditMemoDocument) {
    LOG.debug("Inside Calculation for ProrateItemSurcharge");
    vendorCreditMemoDocument.setProrateBy(vendorCreditMemoDocument.isProrateQty() ? OLEConstants.PRORATE_BY_QTY
            : vendorCreditMemoDocument.isProrateManual() ? OLEConstants.MANUAL_PRORATE
                    : vendorCreditMemoDocument.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR
                            : vendorCreditMemoDocument.isNoProrate() ? OLEConstants.NO_PRORATE : null);
    BigDecimal addChargeItem = BigDecimal.ZERO;
    List<OleCreditMemoItem> item = (List<OleCreditMemoItem>) vendorCreditMemoDocument.getItems();
    for (OleCreditMemoItem 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());
        }// w  w w  . j a v a 2s  . com
    }
    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++) {
        OleCreditMemoItem items = (OleCreditMemoItem) vendorCreditMemoDocument.getItem(i);
        if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                totalItemQuantity = totalItemQuantity.add(items.getItemQuantity().bigDecimalValue());
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
                    || vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    || vendorCreditMemoDocument.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());
                }*/
                newUnitPrice = items.getItemUnitPrice();
                newUnitPriceList.add(newUnitPrice);
                extPrice = newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue());
                totalExtPrice = totalExtPrice.add(extPrice);
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
                if (items.getItemSurcharge() == null) {
                    items.setItemSurcharge(BigDecimal.ZERO);
                }
                totalSurCharge = totalSurCharge
                        .add(items.getItemQuantity().bigDecimalValue().multiply(items.getItemSurcharge()));
            }
        }

    }
    if (vendorCreditMemoDocument.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++) {
        OleCreditMemoItem items = (OleCreditMemoItem) vendorCreditMemoDocument.getItem(i);
        if (items.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (vendorCreditMemoDocument.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.setExtendedPrice(
                        (new KualiDecimal((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                items.setItemSurcharge(
                        itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                items.setExtendedPrice(
                        new KualiDecimal(((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    && items.getItemSurcharge() != null) {
                items.setExtendedPrice(
                        new KualiDecimal(((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            j++;
        }
    }
    if (vendorCreditMemoDocument.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: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()));
    }//w w w .ja  va2  s. c o m

    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.erudika.para.utils.Utils.java

/**
 * Round up a double using the "half up" method
 * @param d a double/*from  w  w w. ja  va  2 s .c  o m*/
 * @param scale the scale
 * @return a double
 */
public static double roundHalfUp(double d, int scale) {
    return BigDecimal.valueOf(d).setScale(scale, RoundingMode.HALF_UP).doubleValue();
}

From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java

private void updateShapeProgress(BigDecimal numFeatures) {
    if (taskEntity.getState().getStatus() == Status.FINISHED) {
        finishState();/*from   ww w.  j a  v  a2 s. c o  m*/
    } else {
        // gets current data
        int readLines = fileProcessor.getNumCurrentEntry();
        int currentNumFeature = fileProcessor.getNumCurrentEntry();

        // calculates the progress
        BigDecimal currentNumFeatureBD = BigDecimal.valueOf(currentNumFeature);
        double progress = currentNumFeatureBD.divide(numFeatures, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100)).doubleValue();

        // updates the task state
        taskEntity.getState().setReadLines(readLines);
        taskEntity.getState().setProgress(progress);

        // finishes when all bytes are read
        if (currentNumFeatureBD.longValue() == numFeatures.longValue()) {
            finishState();
        }
    }
}

From source file:edu.harvard.med.screensaver.service.cherrypicks.CherryPickRequestPlateMapFilesBuilder.java

private void writeCherryPickRow(PrintWriter out, LabCherryPick cherryPick) {
    out.print(cherryPick.getSourceWell().getPlateNumber());
    out.print(cherryPick.getSourceCopy().getName());
    out.print(cherryPick.getSourceWell().getWellName());
    out.print(cherryPick.getSourceCopy().findPlate(cherryPick.getSourceWell().getPlateNumber()).getPlateType());
    out.print(cherryPick.getAssayPlateWellName());
    out.print(cherryPick.getAssayPlate().getAssayPlateType());
    out.print(cherryPick.getCherryPickRequest().getRequestedBy().getFullNameFirstLast());
    out.print(cherryPick.getCherryPickRequest().getScreen().getFacilityId());
    out.print(cherryPick.getCherryPickRequest().getTransferVolumePerWellApproved()
            .convert(VolumeUnit.MICROLITERS).getValue().setScale(2, RoundingMode.HALF_UP));
    out.println();//from w  ww .  ja  v a  2s .  co m
}

From source file:org.kuali.coeus.common.budget.framework.personnel.BudgetPersonnelDetails.java

public ScaleTwoDecimal getPersonMonths() {
    ScaleTwoDecimal result = null;//from w w w  .j  a  v a 2  s . co  m
    if (getStartDate() != null && getEndDate() != null) {
        Calendar startDateCalendar = Calendar.getInstance();
        startDateCalendar.setTime(getStartDate());
        int startMonth = startDateCalendar.get(MONTH);
        Calendar endDateCalendar = Calendar.getInstance();
        endDateCalendar.setTime(getEndDate());
        double personMonths = 0d;
        while (startDateCalendar.compareTo(endDateCalendar) <= 0) {
            double noOfDaysInMonth = startDateCalendar.getActualMaximum(DAY_OF_MONTH);
            double noOfActualDays = 0;
            if (startDateCalendar.get(MONTH) == endDateCalendar.get(MONTH)
                    && startDateCalendar.get(Calendar.YEAR) == endDateCalendar.get(Calendar.YEAR)) {
                noOfActualDays = endDateCalendar.get(DAY_OF_MONTH) - startDateCalendar.get(DAY_OF_MONTH) + 1;
            } else if (startDateCalendar.get(MONTH) == startMonth) {
                noOfActualDays = noOfDaysInMonth - startDateCalendar.get(DAY_OF_MONTH) + 1;
            } else {
                noOfActualDays = noOfDaysInMonth;
            }
            startDateCalendar.add(MONTH, 1);
            startDateCalendar.set(DAY_OF_MONTH, 1);
            personMonths += (noOfActualDays / noOfDaysInMonth);
        }
        result = new ScaleTwoDecimal(new BigDecimal(personMonths).setScale(2, RoundingMode.HALF_UP)
                .multiply(getPercentEffort().bigDecimalValue())
                .divide(new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP));
    }
    return result;
}