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:net.sf.jabb.util.stat.AtomicLongStatistics.java

@Override
public BigDecimal getAvg(int scale) {
    return new BigDecimal(getAvg()).setScale(scale, BigDecimal.ROUND_HALF_UP);
}

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

/**
 * Returns the big decimal for the value and scale.
 * //from w w w  .j  ava 2s.  c  o  m
 * @param value The value.
 * @param decimals The number of decimal places.
 * @return The big decimal.
 */
public static BigDecimal getBigDecimal(double value, int decimals) {
    return new BigDecimal(value).setScale(decimals, BigDecimal.ROUND_HALF_UP);
}

From source file:com.salesmanager.core.util.CurrencyUtil.java

public static BigDecimal validateMeasure(String measure, String currencycode) throws ValidationException {

    try {/* ww  w .  j  a va2 s  .com*/

        if (currencycode == null) {
            currencycode = getDefaultCurrency();
        }

        log.debug("Trying to validate " + measure + " for currency " + currencycode);

        CurrencyModule module = (CurrencyModule) currencyMap.get(currencycode);

        if (module == null) {
            throw new ValidationException("There is no CurrencyModule defined for currency " + currencycode
                    + " in module/impl/application/currencies");
        }

        BigDecimal returnMeasure = module.getAmount(measure);
        returnMeasure.setScale(1, BigDecimal.ROUND_HALF_UP);
        return returnMeasure;

    } catch (Exception e) {
        if (e instanceof ValidationException)
            throw (ValidationException) e;
        throw new ValidationException(e.getMessage());
    }

}

From source file:com.konakart.bl.modules.payment.globalcollect.GlobalCollectUtils.java

/**
 * Calculate the total amount of the order. Some of the payment products are only suitable for a
 * price in a certain range.//from  w  w  w. jav  a2s .  c om
 * 
 * @param order
 * @param scale
 * @return the total amount of the order
 */
public BigDecimal getTotalPrice(OrderIf order, int scale) {
    BigDecimal total = null;

    if (order.getOrderTotals() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot determine total price because order has no order totals yet");
        }
        return total;
    }

    for (int i = 0; i < order.getOrderTotals().length; i++) {
        OrderTotal ot = (OrderTotal) order.getOrderTotals()[i];
        if (ot.getClassName().equals(OrderTotalMgr.ot_total)) {
            total = ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
    }

    return total;
}

From source file:org.bankinterface.util.Utils.java

/**
 * ??,??,,??.// ww w  . j a  v a  2s  .  com
 * 
 * @param amount
 * @return
 */
public static BigDecimal parseFromYuan(String amount) {
    if (amount == null) {
        throw new IllegalArgumentException();
    }
    return new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
}

From source file:Ternary.java

public Ternary(BigInteger toConvert) {
    this();/* w w w . j a v  a  2s. c o m*/
    int position = 0;
    BigInteger remaining = toConvert;
    BigInteger rounded, left;
    while (!remaining.equals(BigInteger.ZERO)) {
        rounded = ((new BigDecimal(remaining)).divide(bdThree, 0, BigDecimal.ROUND_HALF_UP)).toBigInteger();
        left = remaining.subtract(rounded.multiply(biThree));
        if (left.equals(BigInteger.ONE))
            setTrit(position++, Trit.POSITIVE);
        else if (left.equals(BigInteger.ZERO))
            setTrit(position++, Trit.NEUTRAL);
        else
            setTrit(position++, Trit.NEGATIVE);
        remaining = rounded;
    }
}

From source file:com.vangent.hieos.empi.match.ScoredRecord.java

/**
 * //  ww w.j a  va  2 s  .c om
 * @return
 */
public int getMatchScorePercentage() {
    // Round-up match score.
    BigDecimal bd = new BigDecimal(this.getScore() * 100.0);
    bd = bd.setScale(0, BigDecimal.ROUND_HALF_UP);
    return bd.intValue();
}

From source file:io.silverware.microservices.monitoring.MetricsManager.java

/**
 * Method responsible for adding new time to values collection and also updating min, max, avg and count metrics.
 *
 * @param elapsedTime/*from   w  w w  .j  av a2  s  .  c o  m*/
 *       runtime of microservice method.
 */
public void addTime(BigDecimal elapsedTime) {

    if (elapsedTime.compareTo(BigDecimal.ZERO) <= 0) {
        throw new IllegalArgumentException("Elapsed time is negative or zero");
    }

    mapValues.put(longAdder.longValue(), elapsedTime);

    longAdder.increment();

    final BigDecimal count = new BigDecimal(metrics.getCount());
    final BigDecimal averageTime = metrics.getAverageTime();
    final BigDecimal minTime = metrics.getMinTime();
    final BigDecimal maxTime = metrics.getMaxTime();

    metrics.incrementCount();

    metrics.setAverageTime((averageTime.multiply(count).add(elapsedTime)).divide(count.add(BigDecimal.ONE),
            BigDecimal.ROUND_HALF_UP));

    if (elapsedTime.compareTo(maxTime) >= 1) {
        metrics.setMaxTime(elapsedTime);
    } else {
        metrics.setMinTime(elapsedTime);
    }
}

From source file:biz.c24.io.spring.integration.samples.fpml.FpmlGenerator.java

private static TradeConfirmed randomizeFpML(TradeConfirmed tradeConfirmed) throws CloneNotSupportedException {
    ISO8601DateTime creationDate = new ISO8601DateTime(new Date());
    ISO8601Date tradeDate = new ISO8601Date(new GregorianCalendar(2011, Calendar.JULY, 5).getTime());
    ISO8601Date expiryDate = new ISO8601Date(new GregorianCalendar(2012, Calendar.JANUARY, 5).getTime());
    ISO8601Date settlementDate = new ISO8601Date(new GregorianCalendar(2011, Calendar.JULY, 7).getTime());
    ISO8601Date valueDate = new ISO8601Date(new GregorianCalendar(2012, Calendar.JANUARY, 9).getTime());

    Random random = new Random();

    BigDecimal putAmount = new BigDecimal((1 + random.nextInt(999)) * 100000.);
    BigDecimal callAmount = new BigDecimal((1 + random.nextInt(999)) * 100000.);
    BigDecimal fxRate = callAmount.divide(putAmount, 8, RoundingMode.HALF_EVEN).setScale(5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal premiumValue = new BigDecimal(0.001).setScale(5, BigDecimal.ROUND_HALF_UP);
    BigDecimal premiumAmount = callAmount.multiply(premiumValue).setScale(2, BigDecimal.ROUND_HALF_UP);

    String sendTo = "SendTo" + random.nextInt(999999);
    String sentBy = "SentBy" + random.nextInt(999999);
    String msgId = "Msg" + random.nextInt(999999);
    String conversationId = "Conv" + random.nextInt(999999);
    String tradeId1 = "ID1:" + random.nextInt(999999);
    String tradeId2 = "ID2:" + random.nextInt(999999);

    // Set the header
    NotificationMessageHeader header = tradeConfirmed.getHeader();
    header.getMessageHeadermodel().setCreationTimestamp(creationDate);
    header.getConversationId().setValue(conversationId);
    header.getMessageId().setValue(msgId);
    header.getMessageHeadermodel().getSentBy().setValue(sentBy);
    header.getMessageHeadermodel().getSendTo()[0].setValue(sendTo);

    // Set the TradeHeader
    TradeHeader tradeHeader = tradeConfirmed.getTrade().getTradeHeader();
    tradeHeader.getPartyTradeIdentifier()[0].getTradeIdentifierSG1()[0].getTradeId().setValue(tradeId1);
    tradeHeader.getPartyTradeIdentifier()[1].getTradeIdentifierSG1()[0].getTradeId().setValue(tradeId2);
    tradeHeader.getTradeDate().setValue(tradeDate);

    FxOptionLeg fxOptionLeg = (FxOptionLeg) tradeConfirmed.getTrade().getProduct();
    fxOptionLeg.getExpiryDateTime().setExpiryDate(expiryDate);

    FxOptionPremium optionPremium = fxOptionLeg.getFxOptionPremium()[0];
    optionPremium.getPremiumAmount().setAmount(premiumAmount);
    optionPremium.setPremiumSettlementDate(settlementDate);
    SettlementInstruction settlementInstruction = optionPremium.getSettlementInformation()
            .getSettlementInstruction();
    settlementInstruction.getCorrespondentInformation().getRoutingIdentificationmodel().getRoutingIds()
            .getRoutingId()[0].setValue(sendTo);
    settlementInstruction.getBeneficiary().getRoutingIdentificationmodel().getRoutingIds().getRoutingId()[0]
            .setValue(sentBy);/*  ww  w.  ja va  2  s.  co m*/
    optionPremium.getPremiumQuote().setPremiumValue(premiumValue);
    fxOptionLeg.setValueDate(valueDate);

    fxOptionLeg.getPutCurrencyAmount().getCurrency().setValue("AUD");
    fxOptionLeg.getPutCurrencyAmount().setAmount(putAmount);

    fxOptionLeg.getPutCurrencyAmount().getCurrency().setValue("USD");
    fxOptionLeg.getCallCurrencyAmount().setAmount(callAmount);

    fxOptionLeg.getFxStrikePrice().setRate(fxRate);

    fxOptionLeg.getQuotedAs().getOptionOnCurrency().setValue("AUD");
    fxOptionLeg.getQuotedAs().getFaceOnCurrency().setValue("USD");
    fxOptionLeg.getQuotedAs().getQuotedTenor().setPeriod("M");
    fxOptionLeg.getQuotedAs().getQuotedTenor().setPeriodMultiplier(new BigInteger("6"));

    tradeConfirmed.getParty()[0].getPartyId()[0].setValue(sendTo);
    tradeConfirmed.getParty()[1].getPartyId()[0].setValue(sentBy);

    return (TradeConfirmed) tradeConfirmed.cloneDeep();
}

From source file:de.ingrid.importer.udk.strategy.v30.IDCStrategy3_0_0_fixErfassungsgrad.java

private void fixErfassungsgrad() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Fix \"Erfassungsgrad\" (t011_obj_geo.rec_grade) from Commission to Omission...");
    }//  ww w.  j a va2  s  .  c  om

    // sql
    String sql = "select * from t011_obj_geo where rec_grade IS NOT NULL";

    PreparedStatement pS = jdbc.prepareStatement("UPDATE t011_obj_geo SET rec_grade = ? where id = ?");
    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    int numFixed = 0;
    while (rs.next()) {
        long id = rs.getLong("id");
        long objId = rs.getLong("obj_id");
        double oldRecGrade = rs.getDouble("rec_grade");
        double newRecGrade = 100.0 - oldRecGrade;
        if (newRecGrade < 0.0) {
            newRecGrade = 0.0;
            log.warn("New value " + newRecGrade + " < 0, we set new value to 0.0.");
        }
        if (newRecGrade > 100.0) {
            newRecGrade = 100.0;
            log.warn("New value " + newRecGrade + " > 100, we set new value to 100.0.");
        }

        try {
            // round 2 decimals after digit
            newRecGrade = new BigDecimal(newRecGrade).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception ex) {
            log.error("Problems rounding " + newRecGrade
                    + " to 2 decimals after digit, we keep unrounded value." + ex);
        }

        pS.setDouble(1, newRecGrade);
        pS.setLong(2, id);
        int numUpdated = pS.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Fixed t011_obj_geo.rec_grade from " + oldRecGrade + " to " + newRecGrade + " ("
                    + numUpdated + " row(s), objectId: " + objId + ")");
        }
        numFixed++;
    }

    pS.close();
    rs.close();
    st.close();

    if (log.isInfoEnabled()) {
        log.info("Fixed " + numFixed + " times \"Erfassungsgrad\"");
    }

    if (log.isInfoEnabled()) {
        log.info("Fix \"Erfassungsgrad\" (t011_obj_geo.rec_grade) from Commission to Omission...done");
    }
}