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:ch.algotrader.service.ib.IBNativeHistoricalDataServiceImpl.java

@Override
public synchronized List<Bar> getHistoricalBars(long securityId, Date endDate, int timePeriodLength,
        TimePeriod timePeriod, Duration barSize, MarketDataEventType marketDataEventType,
        Map<String, String> properties) {

    Validate.notNull(endDate, "End date is null");
    Validate.notNull(timePeriod, "Time period is null");
    Validate.notNull(barSize, "Bar size is null");
    Validate.notNull(marketDataEventType, "Bar type is null");

    Security security = this.securityDao.get(securityId);
    if (security == null) {
        throw new ServiceException("security was not found: " + securityId);
    }/*w w  w  .j a v  a 2 s.  co  m*/

    int scale = security.getSecurityFamily().getScale(Broker.IB.name());
    Contract contract = IBUtil.getContract(security);
    int requestId = (int) this.requestIdGenerator.generateId();
    String dateString = dateTimeFormat.format(DateTimeLegacy.toLocalDateTime(endDate));

    String durationString = timePeriodLength + " ";
    switch (timePeriod) {
    case SEC:
        durationString += "S";
        break;
    case DAY:
        durationString += "D";
        break;
    case WEEK:
        durationString += "W";
        break;
    case MONTH:
        durationString += "M";
        break;
    case YEAR:
        durationString += "Y";
        break;
    default:
        throw new ServiceException("timePeriod is not allowed " + timePeriod);
    }

    String[] barSizeName = barSize.name().split("_");

    String barSizeString = barSizeName[1] + " ";
    switch (barSizeName[0]) {
    case "SEC":
        barSizeString += "sec";
        break;
    case "MIN":
        barSizeString += "min";
        break;
    case "HOUR":
        barSizeString += "hour";
        break;
    case "DAY":
        barSizeString += "day";
        break;
    default:
        throw new ServiceException("barSize is not allowed " + barSize);
    }

    if (Integer.parseInt(barSizeName[1]) > 1) {
        barSizeString += "s";
    }

    String marketDataEventTypeString;
    switch (marketDataEventType) {
    case TRADES:
        marketDataEventTypeString = "TRADES";
        break;
    case MIDPOINT:
        marketDataEventTypeString = "MIDPOINT";
        break;
    case BID:
        marketDataEventTypeString = "BID";
        break;
    case ASK:
        marketDataEventTypeString = "ASK";
        break;
    case BID_ASK:
        marketDataEventTypeString = "BID_ASK";
        break;
    default:
        throw new ServiceException("unsupported marketDataEventType " + marketDataEventType);
    }

    // avoid pacing violations
    long waitMillis = (this.lastTimeStamp.get() + pacingMillis) - System.currentTimeMillis();
    if (waitMillis > 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("waiting {} seconds until next historical data request",
                    new BigDecimal(((double) waitMillis) / 1000).setScale(2, BigDecimal.ROUND_HALF_EVEN));
        }
        try {
            Thread.sleep(waitMillis);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw new ServiceException(ex);
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Request historic data; request id = {}; security id = {}; conId = {}; date = {}; duration = {}; bar size = {}",
                requestId, securityId, contract.m_conId, dateString, durationString, barSizeString);
    }

    PromiseImpl<List<Bar>> promise = new PromiseImpl<>(null);
    this.pendingRequests.addHistoricDataRequest(requestId, promise);
    this.iBSession.reqHistoricalData(requestId, contract, dateString, durationString, barSizeString,
            marketDataEventTypeString, this.iBConfig.useRTH() ? 1 : 0, 1, Collections.<TagValue>emptyList());
    List<Bar> bars = getBarsBlocking(promise);

    this.lastTimeStamp.set(System.currentTimeMillis());

    // set & update fields
    for (Bar bar : bars) {
        bar.setSecurity(security);
        bar.setFeedType(FeedType.IB.name());
        bar.getOpen().setScale(scale, RoundingMode.HALF_UP);
        bar.getHigh().setScale(scale, RoundingMode.HALF_UP);
        bar.getLow().setScale(scale, RoundingMode.HALF_UP);
        bar.getClose().setScale(scale, RoundingMode.HALF_UP);
        bar.getVwap().setScale(scale, RoundingMode.HALF_UP);
        bar.setBarSize(barSize);
    }
    return bars;
}

From source file:uk.ac.leeds.ccg.andyt.projects.fluvialglacial.SlopeAreaAnalysis.java

protected TreeMap<Integer, Object[]> readSwissData(File fileIn) {
    TreeMap<Integer, Object[]> result;
    result = new TreeMap<Integer, Object[]>();
    BufferedReader br;//from   w  w w  . ja v  a  2s  . co m
    br = Generic_StaticIO.getBufferedReader(fileIn);
    StreamTokenizer st;
    st = new StreamTokenizer(br);
    Generic_StaticIO.setStreamTokenizerSyntax5(st);
    st.wordChars('(', '(');
    st.wordChars(')', ')');
    st.wordChars('%', '%');
    Generic_StaticIO.skipline(st);
    int token;
    String line = "";
    String[] fields;
    try {
        token = st.nextToken();
        int ID;
        //int pointID;
        while (token != StreamTokenizer.TT_EOF) {
            switch (token) {
            case StreamTokenizer.TT_EOL:
                //flowacc,area (km2),slope_25_(%),proglac_ID,COUNT
                //12.11111069,0.00756944,32.33880000000,0,250631
                fields = line.split(sComma);
                ID = Integer.valueOf(fields[3]);
                if (ID > 0) {
                    //BigDecimal flowacc;
                    BigDecimal area;
                    BigDecimal slope;
                    Object[] data;
                    BigDecimal maxx;
                    BigDecimal maxy;
                    BigDecimal minx;
                    BigDecimal miny;
                    data = result.get(ID);
                    ArrayList<Generic_XYNumericalData> theGeneric_XYNumericalData;
                    if (data == null) {
                        data = new Object[5];
                        theGeneric_XYNumericalData = new ArrayList<Generic_XYNumericalData>();
                        maxx = BigDecimal.ZERO;
                        maxy = BigDecimal.ZERO;
                        minx = BigDecimal.valueOf(Double.MAX_VALUE);
                        miny = BigDecimal.valueOf(Double.MAX_VALUE);
                        data[0] = theGeneric_XYNumericalData;
                        data[1] = maxx;
                        data[2] = minx;
                        data[3] = maxy;
                        data[4] = miny;
                        result.put(ID, data);
                    } else {
                        theGeneric_XYNumericalData = (ArrayList<Generic_XYNumericalData>) data[0];
                        maxx = (BigDecimal) data[1];
                        minx = (BigDecimal) data[2];
                        maxy = (BigDecimal) data[3];
                        miny = (BigDecimal) data[4];
                    }
                    //pointID = Integer.valueOf(fields[4]);
                    //flowacc = new BigDecimal(fields[0]);
                    area = new BigDecimal(fields[1]);
                    if (area.compareTo(BigDecimal.ZERO) == 1) {
                        area = Generic_BigDecimal.log(10, area, 10, RoundingMode.HALF_UP);
                    } else {
                        area = BigDecimal.ZERO;
                    }
                    slope = new BigDecimal(fields[2]);
                    if (slope.compareTo(BigDecimal.ZERO) == 1) {
                        slope = Generic_BigDecimal.log(10, slope, 10, RoundingMode.HALF_UP);
                    } else {
                        slope = BigDecimal.ZERO;
                    }
                    Generic_XYNumericalData point;
                    point = new Generic_XYNumericalData(slope, area);
                    theGeneric_XYNumericalData.add(point);
                    data[0] = theGeneric_XYNumericalData;
                    data[1] = maxx.max(slope);
                    data[2] = minx.min(slope);
                    data[3] = maxy.max(area);
                    data[4] = miny.min(area);
                }
                break;
            case StreamTokenizer.TT_WORD:
                line = st.sval;
                break;
            }
            token = st.nextToken();
        }
    } catch (IOException ex) {
        Logger.getLogger(SlopeAreaAnalysis.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:dom.rootlocus.utils.Utils.java

public Complex[] getRootsSimplified(Complex[] r) {
    //        int pCompRoots = countComplexPairRoots(r);
    ArrayList<Complex> sr = new ArrayList<>();

    for (int i = 0; i < r.length; i++) {
        if (r[i].getImaginary() == 0) {
            sr.add(r[i]);// w ww .j ava2s  . co  m
        } else {
            Iterator it = sr.iterator();
            int count = 0;
            while (it.hasNext()) {
                Complex c = (Complex) it.next();
                double Re = new BigDecimal(c.getReal()).setScale(4, RoundingMode.HALF_UP).doubleValue();
                double Img = new BigDecimal(c.getImaginary()).setScale(4, RoundingMode.HALF_UP).doubleValue();
                double rootRe = new BigDecimal(r[i].getReal()).setScale(4, RoundingMode.HALF_UP).doubleValue();
                double rootImg = new BigDecimal(r[i].getImaginary()).setScale(4, RoundingMode.HALF_UP)
                        .doubleValue();
                if (Re == rootRe && (Img == rootImg || Img == -rootImg)) {
                    count++;
                    break;
                }
            }
            if (count == 0) {
                sr.add(r[i]);
            }

        }
    }
    return sr.toArray(new Complex[sr.size()]);
}

From source file:org.businessmanager.web.controller.page.invoice.InvoiceEditController.java

public BigDecimal getTotalVatAmount() {
    BigDecimal totalVatAmount = BigDecimal.ZERO;
    for (LineItemBean lineItem : bean.getLineItems()) {
        BigDecimal amount = lineItem.getVatAmount();
        totalVatAmount = totalVatAmount.add(amount);
    }//  w ww  .j  ava2s . c  om

    return totalVatAmount.setScale(2, RoundingMode.HALF_UP);
}

From source file:org.openhab.binding.pilight.internal.PilightBinding.java

private void setDimmerValue(PercentType percent, Code code) {
    if (BigDecimal.ZERO.equals(percent.toBigDecimal())) {
        // pilight is not responding to commands that set both the dimlevel to 0 and state to off. 
        // So, we're only updating the state for now 
        code.setState(Code.STATE_OFF);/*from w  ww .java 2 s . c  o m*/
    } else {
        BigDecimal dimlevel = new BigDecimal(percent.toBigDecimal().toString()).setScale(2)
                .divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(MAX_DIM_LEVEL)).setScale(0, RoundingMode.HALF_UP);

        Values values = new Values();
        values.setDimlevel(dimlevel.intValue());
        code.setValues(values);
        code.setState(dimlevel.compareTo(BigDecimal.ZERO) == 1 ? Code.STATE_ON : Code.STATE_OFF);
    }
}

From source file:org.yes.cart.shoppingcart.impl.WeightBasedPriceListDeliveryCostCalculationStrategy.java

/** {@inheritDoc} */
public Total calculate(final MutableShoppingCart cart) {

    if (!cart.getCarrierSlaId().isEmpty()) {

        Total total = null;/* ww w. j av a  2  s.co m*/

        for (final Map.Entry<String, Long> supplierCarrierSla : cart.getCarrierSlaId().entrySet()) {

            final Map<DeliveryBucket, List<CartItem>> cartBuckets = new HashMap<DeliveryBucket, List<CartItem>>();
            for (final Map.Entry<DeliveryBucket, List<CartItem>> bucket : cart.getCartItemMap().entrySet()) {
                // Add shipping line for every bucket by this supplier (e.g. if we have multi delivery)
                if (bucket.getKey().getSupplier().equals(supplierCarrierSla.getKey())) {
                    cartBuckets.put(bucket.getKey(), bucket.getValue());
                }

            }

            if (cartBuckets.isEmpty()) {
                continue; // no buckets for this selection
            }

            final CarrierSla carrierSla = carrierSlaService.getById(supplierCarrierSla.getValue());
            if (carrierSla != null && CarrierSla.WEIGHT_VOLUME.equals(carrierSla.getSlaType())) {

                final String carrierSlaGUID = carrierSla.getGuid();
                final String carrierSlaName = new FailoverStringI18NModel(carrierSla.getDisplayName(),
                        carrierSla.getName()).getValue(cart.getCurrentLocale());

                final PricingPolicyProvider.PricingPolicy policy = pricingPolicyProvider.determinePricingPolicy(
                        cart.getShoppingContext().getShopCode(), cart.getCurrencyCode(),
                        cart.getCustomerEmail(), cart.getShoppingContext().getCountryCode(),
                        cart.getShoppingContext().getStateCode());

                final BigDecimal qty = QTY;

                for (final Map.Entry<DeliveryBucket, List<CartItem>> bucketAndItems : cartBuckets.entrySet()) {
                    // Add shipping line for every bucket by this supplier (e.g. if we have multi delivery)

                    final Pair<BigDecimal, BigDecimal> weightAndVolume = determineProductWeightAndVolume(
                            bucketAndItems.getValue());

                    final boolean useWeight = MoneyUtils.isFirstBiggerThanSecond(weightAndVolume.getFirst(),
                            BigDecimal.ZERO);
                    final boolean useVolume = MoneyUtils.isFirstBiggerThanSecond(weightAndVolume.getSecond(),
                            BigDecimal.ZERO);

                    final SkuPrice priceByWeightMax = useWeight
                            ? getSkuPrice(cart, carrierSlaGUID + "_KGMAX", policy, MAX)
                            : null;
                    final SkuPrice priceByWeight = useWeight && isValidPrice(priceByWeightMax)
                            && MoneyUtils.isFirstBiggerThanOrEqualToSecond(priceByWeightMax.getQuantity(),
                                    weightAndVolume.getFirst())
                                            ? getSkuPrice(cart, carrierSlaGUID + "_KG", policy,
                                                    weightAndVolume.getFirst())
                                            : null;
                    final SkuPrice priceByVolumeMax = useVolume
                            ? getSkuPrice(cart, carrierSlaGUID + "_M3MAX", policy, MAX)
                            : null;
                    final SkuPrice priceByVolume = useVolume && isValidPrice(priceByVolumeMax)
                            && MoneyUtils.isFirstBiggerThanOrEqualToSecond(priceByVolumeMax.getQuantity(),
                                    weightAndVolume.getSecond())
                                            ? getSkuPrice(cart, carrierSlaGUID + "_M3", policy,
                                                    weightAndVolume.getSecond())
                                            : null;

                    SkuPrice price = null;
                    if (useWeight && useVolume) {

                        if (isValidPrice(priceByWeight) && isValidPrice(priceByVolume)) {
                            // Assign price only if we have both valid prices

                            final BigDecimal salePriceByWeight = MoneyUtils.minPositive(
                                    priceByWeight.getRegularPrice(),
                                    priceByWeight.getSalePriceForCalculation());
                            final BigDecimal salePriceByVolume = MoneyUtils.minPositive(
                                    priceByVolume.getRegularPrice(),
                                    priceByVolume.getSalePriceForCalculation());

                            if (MoneyUtils.isFirstBiggerThanOrEqualToSecond(salePriceByVolume,
                                    salePriceByWeight)) {
                                // Volume has higher cost
                                price = priceByVolume;
                            } else {
                                // Weight has higher cost
                                price = priceByWeight;
                            }

                        }

                    } else if (useWeight) {
                        // Only weight is available
                        price = priceByWeight;
                    } else if (useVolume) {
                        // Only volume is available
                        price = priceByVolume;
                    }

                    if (isValidPrice(price)) {

                        final BigDecimal salePrice = MoneyUtils.minPositive(price.getRegularPrice(),
                                price.getSalePriceForCalculation());

                        cart.addShippingToCart(bucketAndItems.getKey(), carrierSlaGUID, carrierSlaName, qty);
                        cart.setShippingPrice(carrierSlaGUID, bucketAndItems.getKey(), salePrice, salePrice);
                        final BigDecimal deliveryCost = salePrice.multiply(qty)
                                .setScale(Constants.DEFAULT_SCALE, RoundingMode.HALF_UP);

                        final Total bucketTotal = new TotalImpl(Total.ZERO, Total.ZERO, Total.ZERO, Total.ZERO,
                                false, null, Total.ZERO, Total.ZERO, Total.ZERO, deliveryCost, deliveryCost,
                                false, null, Total.ZERO, deliveryCost, deliveryCost, Total.ZERO, deliveryCost,
                                deliveryCost);

                        // Add bucket total to delivery cost
                        total = total == null ? bucketTotal : total.add(bucketTotal);

                    } else {
                        // If at least one bucket cannot be delivered, none should
                        return null;

                    }
                }

            }
        }

        return total;
    }
    return null;
}

From source file:org.cirdles.ambapo.UTMToLatLong.java

/**
 * /*from   w w w .j av  a2s . co m*/
 * @param originalTau
 * @param sigma
 * @param eccentricity
 * @param hemisphere
 * @return latitude
 */
private static BigDecimal calcLatitude(BigDecimal originalTau, BigDecimal sigma, BigDecimal eccentricity,
        char hemisphere) {

    BigDecimal funcOfTau = functionOfTau(originalTau, sigma, originalTau).setScale(PRECISION,
            RoundingMode.HALF_UP);

    BigDecimal changeInTau = changeInTau(eccentricity, originalTau, sigma);

    BigDecimal newTau = originalTau.subtract(funcOfTau.divide(changeInTau, PRECISION, RoundingMode.HALF_UP));

    BigDecimal latitude = (new BigDecimal(Math.atan(newTau.doubleValue())))
            .multiply(new BigDecimal(180.0 / Math.PI));

    if (hemisphere == 'S')
        latitude = latitude.multiply(new BigDecimal(-1));

    return latitude;

}

From source file:org.eclipse.smarthome.binding.meteoblue.handler.MeteoBlueHandler.java

/**
 * Update the channel from the last weather data retrieved.
 *
 * @param channelId the id of the channel to be updated
 *///  w w  w . j  a va  2  s.  c o  m
private void updateChannel(String channelId) {
    Channel channel = getThing().getChannel(channelId);
    if (channel == null || !isLinked(channelId)) {
        logger.trace("Channel '{}' was null or not linked! Not updated.", channelId);
        return;
    }

    // get the set of channel parameters.
    // the first will be the forecast day (eg. forecastToday),
    // and the second will be the datapoint (eg. snowFraction)
    String[] channelParts = channelId.split("#");
    String forecastDay = channelParts[0];
    String datapointName = channelParts[1];
    if (channelParts.length != 2) {
        logger.debug("Skipped invalid channelId '{}'", channelId);
        return;
    }

    logger.debug("Updating channel '{}'", channelId);
    Forecast forecast = getForecast(forecastDay);
    if (forecast == null) {
        logger.debug("No forecast found for '{}'. Not updating.", forecastDay);
        return;
    }

    Object datapoint = forecast.getDatapoint(datapointName);
    logger.debug("Value for datapoint '{}' is '{}'", datapointName, datapoint);
    if (datapoint == null) {
        logger.debug("Couldn't get datapoint '{}' for '{}'. Not updating.", datapointName, forecastDay);
        return;
    }

    // Build a State from this value
    State state = null;
    if (datapoint instanceof Calendar) {
        state = new DateTimeType((Calendar) datapoint);
    } else if (datapoint instanceof Integer) {
        state = getStateForType(channel.getAcceptedItemType(), (Integer) datapoint);
    } else if (datapoint instanceof Number) {
        BigDecimal decimalValue = new BigDecimal(datapoint.toString()).setScale(2, RoundingMode.HALF_UP);
        state = getStateForType(channel.getAcceptedItemType(), decimalValue);
    } else if (datapoint instanceof String) {
        state = new StringType(datapoint.toString());
    } else if (datapoint instanceof BufferedImage) {
        ImageItem item = new ImageItem("rain area");
        state = new RawType(renderImage((BufferedImage) datapoint), "image/png");
        item.setState(state);
    } else {
        logger.debug("Unsupported value type {}", datapoint.getClass().getSimpleName());
    }

    // Update the channel
    if (state != null) {
        logger.trace("Updating channel with state value {}. (object type {})", state,
                datapoint.getClass().getSimpleName());
        updateState(channelId, state);
    }
}

From source file:org.kuali.ole.select.document.web.struts.OleInvoiceAction.java

/**
 * @see org.kuali.ole.module.purap.document.web.struts.AccountsPayableActionBase#calculate(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w  ww  .  j a v  a 2 s  .  c  om*/
@Override
public ActionForward calculate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // ActionForward forward = super.calculate(mapping, form, request, response);
    /* calculateCurrency(mapping, form, request, response); */
    OleInvoiceForm paymentForm = (OleInvoiceForm) form;
    OleInvoiceDocument payDoc = (OleInvoiceDocument) paymentForm.getDocument();
    payDoc.setProrateBy(payDoc.isProrateQty() ? OLEConstants.PRORATE_BY_QTY
            : payDoc.isProrateManual() ? OLEConstants.MANUAL_PRORATE
                    : payDoc.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR : null);
    boolean manualProrateValidFlag = true;
    if ((payDoc.getProrateBy() != null) && (payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)
            || payDoc.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
            || payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE))) {
        if (payDoc.getProrateBy() != null && payDoc.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
            // Validates the prorate surchanges if prorate by manual
            manualProrateValidFlag = getOleInvoiceService().validateProratedSurcharge(payDoc);
        }
        if (manualProrateValidFlag) {

            List<OleInvoiceItem> item = payDoc.getItems();
            if (payDoc.getVendorDetail() == null || (payDoc.getVendorDetail() != null
                    && payDoc.getVendorDetail().getVendorHeader().getVendorForeignIndicator() != true)) {
                for (int i = 0; item.size() > i; i++) {
                    OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
                    if (items.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
                        boolean rulePassed = getKualiRuleService()
                                .applyRules(new OleDiscountInvoiceEvent(payDoc, items));
                        if (rulePassed) {
                            items.setItemUnitPrice(
                                    SpringContext.getBean(OlePurapService.class).calculateDiscount(items));
                        }
                    }
                }
            } else {

                LOG.debug("###########Foreign Currency Field Calculation###########");
                for (int i = 0; item.size() > i; i++) {
                    OleInvoiceItem items = (OleInvoiceItem) payDoc.getItem(i);
                    Long id = payDoc.getVendorDetail().getCurrencyType().getCurrencyTypeId();
                    Map documentNumberMap = new HashMap();
                    documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, id);
                    BusinessObjectService businessObjectService = SpringContext
                            .getBean(BusinessObjectService.class);
                    List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(
                            OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE,
                            false);
                    Iterator iterator = exchangeRateList.iterator();
                    if (iterator.hasNext()) {
                        OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
                        items.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
                        payDoc.setForeignVendorInvoiceAmount(payDoc.getVendorInvoiceAmount().bigDecimalValue()
                                .multiply(tempOleExchangeRate.getExchangeRate()));
                    }
                    if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())) {
                        boolean rulePassed = getKualiRuleService()
                                .applyRules(new OleForeignCurrencyInvoiceEvent(payDoc, items));
                        if (rulePassed) {
                            SpringContext.getBean(OlePurapService.class).calculateForeignCurrency(items);
                            if (items.getItemExchangeRate() != null && items.getItemForeignUnitCost() != null) {
                                items.setItemUnitCostUSD(new KualiDecimal(items.getItemForeignUnitCost()
                                        .bigDecimalValue().divide(items.getItemExchangeRate().bigDecimalValue(),
                                                4, RoundingMode.HALF_UP)));
                                items.setItemUnitPrice(items.getItemUnitCostUSD().bigDecimalValue());
                                items.setItemListPrice(items.getItemUnitCostUSD());
                                items.setPurchaseOrderItemUnitPrice(items.getItemUnitPrice());
                            }
                        }

                    } else {
                        if (items.getItemExchangeRate() != null
                                && items.getForeignCurrencyExtendedPrice() != null) {
                            // added for jira - OLE-2203
                            if (items.isAdditionalChargeUsd()) {
                                items.setItemUnitPrice(
                                        items.getForeignCurrencyExtendedPrice().bigDecimalValue());
                            } else {
                                items.setItemUnitPrice(items.getForeignCurrencyExtendedPrice().bigDecimalValue()
                                        .divide(items.getItemExchangeRate().bigDecimalValue(), 4,
                                                RoundingMode.HALF_UP));
                            }
                        }
                    }
                }
            }
            getOleInvoiceService().calculateProrateItemSurcharge(payDoc);
        }
    }

    if (payDoc.getProrateBy() == null && manualProrateValidFlag) {
        getOleInvoiceService().calculateWithoutProrates(payDoc);
    }

    return super.calculate(mapping, form, request, response);
}

From source file:com.sunchenbin.store.feilong.core.lang.NumberUtil.java

/**
 *  one/two,? {@link RoundingMode#HALF_UP},??.
 * //ww w .j  a  v  a2  s.co  m
 * <p>
 * two0,one<br>
 * ?one/two,?,??.
 * </p>
 * 
 * @param one
 *            
 * @param two
 *            ,?BigDecimal??
 * @param scale
 *            ? BigDecimal ,??
 * @return two 0,one<br>
 *         ?one/two,? {@link RoundingMode#HALF_UP},??
 * @see <a href="#RoundingMode">JAVA 8??</a>
 * @see java.math.RoundingMode#HALF_UP
 * @see java.math.BigDecimal#ROUND_HALF_UP
 */
public static BigDecimal getDivideValue(BigDecimal one, Serializable two, int scale) {
    RoundingMode roundingMode = RoundingMode.HALF_UP;
    return getDivideValue(one, two, scale, roundingMode);
}