Example usage for java.math RoundingMode HALF_EVEN

List of usage examples for java.math RoundingMode HALF_EVEN

Introduction

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

Prototype

RoundingMode HALF_EVEN

To view the source code for java.math RoundingMode HALF_EVEN.

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:com.expressui.domain.ecbfx.EcbfxService.java

public BigDecimal convert(BigDecimal amount, String sourceCurrencyCode, String targetCurrencyCode)
        throws IllegalCurrencyException {

    if (sourceCurrencyCode.equals(targetCurrencyCode))
        return amount;

    Map<String, BigDecimal> rates = getFXRates();
    BigDecimal inverseRate = rates.get(sourceCurrencyCode);
    if (inverseRate == null)
        throw new IllegalCurrencyException("Unknown currency: " + sourceCurrencyCode);

    BigDecimal sourceRate = new BigDecimal(1).divide(inverseRate, 10, RoundingMode.HALF_EVEN);
    CurrencyUnit sourceCurrencyUnit = CurrencyUnit.of(sourceCurrencyCode);
    Money amountInSourceCurrency = Money.of(sourceCurrencyUnit, amount, RoundingMode.HALF_EVEN);
    Money amountInEuros;/*from   www .  j a v  a  2s  .  c  o m*/
    if (sourceCurrencyUnit.getCurrencyCode().equals("EUR")) {
        amountInEuros = amountInSourceCurrency;
    } else {
        amountInEuros = amountInSourceCurrency.convertedTo(CurrencyUnit.of("EUR"), sourceRate,
                RoundingMode.HALF_EVEN);
    }

    BigDecimal targetRate = rates.get(targetCurrencyCode);
    if (targetRate == null)
        throw new IllegalCurrencyException("Unknown currency: " + targetCurrencyCode);

    Money amountInTargetCurrency = amountInEuros.convertedTo(CurrencyUnit.of(targetCurrencyCode), targetRate,
            RoundingMode.HALF_EVEN);

    return amountInTargetCurrency.getAmount();
}

From source file:net.sourceforge.fenixedu.domain.Guide.java

public void updateTotalValue() {

    BigDecimal total = BigDecimal.ZERO;

    for (final GuideEntry guideEntry : getGuideEntriesSet()) {
        total = total//from  w  ww .j  a va 2s  . c o m
                .add(guideEntry.getPriceBigDecimal().multiply(BigDecimal.valueOf(guideEntry.getQuantity())));
    }

    total.setScale(2, RoundingMode.HALF_EVEN);

    setTotalBigDecimal(total);

}

From source file:com.benfante.minimark.blo.ResultCalculationBo.java

/**
 * Evaluate an assessment normalizing the sum of the marks of each question
 * to a maximum value.//from  w ww  .ja  v a 2 s  .c om
 *
 * @param assessment The assessment to evaluate.
 * @param maxValue The maximum value to wich normalize. If it's null, the default is 100.
 * @return The evaluation
 */
public BigDecimal calculateNormalizedSum(AssessmentFilling assessment, BigDecimal maxValue) {
    if (maxValue == null) {
        maxValue = new BigDecimal("100.00");
    }
    BigDecimal result = new BigDecimal("0.00");
    for (QuestionFilling questionFilling : assessment.getQuestions()) {
        result = addQuestionMarkedWeight(questionFilling, result);
    }
    final BigDecimal totalWeight = assessment.getTotalWeight();
    if (!BigDecimal.ZERO.equals(totalWeight)) {
        result = result.multiply(maxValue).divide(totalWeight, 2, RoundingMode.HALF_EVEN);
    }
    return result;
}

From source file:it.polimi.diceH2020.SPACE4Cloud.shared.solution.SolutionPerJob.java

public void setCost() {
    double cost = deltaBar * numOnDemandVM + rhoBar * numReservedVM + sigmaBar * numSpotVM
            + job.getPenalty() * (job.getHup() - numberUsers);
    BigDecimal c = BigDecimal.valueOf(cost).setScale(4, RoundingMode.HALF_EVEN);
    this.cost = c.doubleValue();
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java

private void init() throws IOException {
    doubleMathContext = new MathContext(DIGITS_OF_PRECISION_DOUBLE, RoundingMode.HALF_EVEN);
    firstNumCharSet.addAll(/*from ww w  .j a  v a  2 s  .  co m*/
            Arrays.asList(new Character[] { '+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }));
}

From source file:com.github.sarxos.xchange.impl.FetchOpenExchangeImpl.java

private static Collection<ExchangeRate> read(String json, String to, Collection<String> from)
        throws JsonProcessingException, IOException {

    // example JSON

    // {/*from  ww w.  j a  v  a2s . c  om*/
    // "disclaimer": "...",
    // "license": "...",
    // "timestamp": 1427716861,
    // "base": "USD",
    // "rates": {
    // "AED": 3.67305,
    // "AFN": 57.780167,
    // "ALL": 129.4859,
    // "AMD": 471.586001,
    // "ANG": 1.78948,
    // "AOA": 107.97125,
    // ... etc for more symbols

    LOG.trace("Reading JSON tree: {}", json);

    JsonNode root = MAPPER.readTree(json);
    if (root == null) {
        throw new IOException("Invalid JSON received: " + json);
    }

    JsonNode rates = root.get("rates");
    if (rates == null) {
        throw new IOException("No rate element has been found in received JSON: " + json);
    }

    Iterator<Entry<String, JsonNode>> entries = rates.fields();
    Map<String, BigDecimal> currencies = new HashMap<>();

    while (entries.hasNext()) {

        Entry<String, JsonNode> entry = entries.next();
        String symbol = entry.getKey();
        String value = entry.getValue().asText();

        currencies.put(symbol, new BigDecimal(value));
    }

    BigDecimal base = currencies.get(to);
    Set<ExchangeRate> exchangerates = new HashSet<>();

    for (Entry<String, BigDecimal> entry : currencies.entrySet()) {

        String symbol = entry.getKey();

        if (!from.contains(symbol)) {
            continue;
        }

        BigDecimal rate = entry.getValue();
        BigDecimal newrate = rate.divide(base, 8, RoundingMode.HALF_EVEN);

        exchangerates.add(new ExchangeRate(to + symbol, newrate.toString()));
    }

    return exchangerates;
}

From source file:se.urvancevav.divider.ListViewFragment.java

private void recalculateSums() {
    BigDecimal total = new BigDecimal(0);
    // Recalculate total sum
    for (int idx = 0; idx < listViewAdapter.getCount(); idx++) {
        ListItem listItem = listViewAdapter.getItem(idx);
        total = total.add(listItem.getPaidAmount());
    }/*w w  w  . j av a 2 s.  c o  m*/

    BigDecimal meanValue = BigDecimal.ZERO;
    if (!listViewAdapter.isEmpty()) {
        meanValue = total.divide(new BigDecimal(listViewAdapter.getCount()),
                Currency.getInstance(Locale.getDefault()).getDefaultFractionDigits(), RoundingMode.HALF_EVEN);
    }

    for (int idx = 0; idx < listViewAdapter.getCount(); idx++) {
        ListItem listItem = listViewAdapter.getItem(idx);
        listItem.setReturnAmount(listItem.getPaidAmount().subtract(meanValue));
    }

    listViewAdapter.notifyDataSetChanged();
}

From source file:com.icoin.trading.tradeengine.domain.events.trade.TradeExecutedEvent.java

@Override
public boolean equals(Object obj) {
    if (obj == this)
        return true;
    if (obj == null) {
        return false;
    }//from   w  ww  .j a va 2 s. co m

    if (!TradeExecutedEvent.class.isAssignableFrom(obj.getClass())) {
        return false;
    }

    TradeExecutedEvent other = (TradeExecutedEvent) obj;

    return new EqualsBuilder()
            .append(tradeAmount.toMoney(RoundingMode.HALF_EVEN),
                    other.tradeAmount.toMoney(RoundingMode.HALF_EVEN))
            .append(tradedPrice.toMoney(RoundingMode.HALF_EVEN),
                    other.tradedPrice.toMoney(RoundingMode.HALF_EVEN))
            .append(buyOrderId, other.buyOrderId).append(sellOrderId, other.sellOrderId)
            .append(sellTransactionId, other.sellTransactionId).append(buyTransactionId, other.buyTransactionId)
            .append(orderBookId, other.orderBookId).append(coinId, other.coinId)
            .append(tradeType, other.tradeType).build();

}

From source file:org.mifos.platform.cashflow.ui.model.CashFlowValidator.java

private void validateIndebtednessRatio(CashFlowForm cashFlowForm, MessageContext messageContext) {
    if (cashFlowForm.shouldForValidateIndebtednessRate()) {
        Double indebtednessRatio = cashFlowForm.getIndebtednessRatio();
        BigDecimal loanAmount = cashFlowForm.getLoanAmount();
        BigDecimal totalCapital = cashFlowForm.getTotalCapital();
        BigDecimal totalLiability = cashFlowForm.getTotalLiability();
        Double calculatedIndebtednessRatio = totalLiability.add(loanAmount).multiply(CashFlowConstants.HUNDRED)
                .divide(totalCapital, 2, RoundingMode.HALF_EVEN).doubleValue();
        if (calculatedIndebtednessRatio >= indebtednessRatio) {
            String message = format(
                    "Indebtedness rate of the client is {0} which should be lesser than the allowable value of {1}",
                    calculatedIndebtednessRatio, indebtednessRatio);
            constructErrorMessage(CashFlowConstants.INDEBTEDNESS_RATIO_MORE_THAN_ALLOWED, message,
                    messageContext, calculatedIndebtednessRatio, indebtednessRatio);
        }/*w  ww  . j  ava  2  s . c om*/
    }
}

From source file:org.kuali.kpme.core.job.JobBo.java

public BigDecimal getFte() {
    if (this.standardHours != null) {
        return this.standardHours.divide(new BigDecimal(40)).setScale(2, RoundingMode.HALF_EVEN);
    } else {//from   www. ja  va2s. c o m
        return fte;
    }
}