Java tutorial · Beginner · 12 min

Handling money in Java: BigDecimal, rounding and currencies

One cent out in a reconciliation means a day of investigation for the back office. These are the rules we apply on every banking project to represent, calculate, round and exchange amounts in Java.

Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)

1. Never use double for an amount

The float and double types store binary fractions: 0.1 has no exact representation.

System.out.println(0.1 + 0.2);          // 0.30000000000000004
System.out.println(1.10 - 1.00);         // 0.10000000000000009

Over a million operations these errors add up and end up showing. For an amount, use java.math.BigDecimal, which stores an integer and a scale (the number of decimal places): 12.34 is 1234 at scale 2.

2. BigDecimal or double: which one?

The rule fits in one sentence: BigDecimal for what gets booked, double for what gets estimated.

Which type for which use
UseTypeWhy
Balances, transfers, fees, interest payable, invoicesBigDecimalMust be exact to the cent and reconcile with accounting
Regulatory reports, client statementsBigDecimalThe amounts are checked by third parties
Contractual rate applied to an amount (FX, interest)BigDecimalThe number of decimals of the rate is part of the contract
Valuation (Black-Scholes, Monte Carlo), sensitivities, VaRdoubleThe result is an estimate: the model's error far exceeds the double's
Curve interpolation, statistics, machine learningdoubleCompute-intensive; the libraries (Strata, maths libraries) work in double
Matching engine, ultra-low-latency order booklong in the smallest unitExact and allocation-free: cents, or multiples of the tick size

A double gives 15 to 16 significant digits: plenty for a model price. Its flaws show when you require exact equality, when you add up millions of amounts, or when the result is compared with another system. BigDecimal is exact but much slower, and creates an object on every operation: avoid it at the heart of a Monte Carlo simulation.

Handle the boundary in one place: when a model result becomes an amount to pay or book (a premium, a margin call, a settlement amount), convert it and round it once, following the contract's rule:

double modelPremium = pricer.premium(option);                  // model estimate
BigDecimal invoicedPremium = BigDecimal.valueOf(modelPremium)
        .setScale(2, RoundingMode.HALF_UP);                    // invoiced amount, contract rule

And never the other way round: a booked amount does not go back through a double for an intermediate calculation.

3. Creating a BigDecimal properly

new BigDecimal(0.1);         // 0.1000000000000000055511151231257827...: the double's error is copied
new BigDecimal("0.1");       // 0.1: from a string, exact
BigDecimal.valueOf(0.1);     // 0.1: goes through Double.toString, acceptable for a constant
BigDecimal.valueOf(1234, 2); // 12.34: from cents stored in a long

Simple rule: amounts arrive as strings (file, JSON, database) or as integer cents, never as a double.

4. Rounding: choose the rule, write it down

Rounding is never implicit. Choose the scale and the mode, and write them in the code:

BigDecimal interest = new BigDecimal("1234.565");
interest.setScale(2, RoundingMode.HALF_UP);    // 1234.57: "commercial" rounding
interest.setScale(2, RoundingMode.HALF_EVEN);  // 1234.56: "banker's" rounding, to the even digit
interest.setScale(2, RoundingMode.DOWN);       // 1234.56: truncation

HALF_EVEN avoids an upward bias when rounding millions of lines; HALF_UP is often the one in contracts and fee schedules. The right rule depends on the product, the contract or the applicable text: ask the business analysts and document it next to the calculation.

Division must always state its rounding, or it fails as soon as the result does not terminate:

BigDecimal hundred = new BigDecimal("100");
hundred.divide(new BigDecimal("3"));                            // ArithmeticException: Non-terminating decimal expansion
hundred.divide(new BigDecimal("3"), 2, RoundingMode.HALF_EVEN); // 33.33
hundred.divide(new BigDecimal("3"), MathContext.DECIMAL128);    // 33.33333333333333333333333333333333 (34 digits)

For intermediate calculations (rates, pro rata), keep precision with MathContext.DECIMAL128 and round only once, on the final amount.

5. Comparing: compareTo, not equals

new BigDecimal("2.0").equals(new BigDecimal("2.00"));        // false: the scale differs
new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0; // true

The trap shows up in HashSets, HashMap keys and tests: with AssertJ, prefer isEqualByComparingTo. If an amount must be used as a key, normalise its scale first with setScale.

6. Not every currency has two decimals

Currency.getInstance("EUR").getDefaultFractionDigits(); // 2
Currency.getInstance("JPY").getDefaultFractionDigits(); // 0
Currency.getInstance("KWD").getDefaultFractionDigits(); // 3

Do not hard-code "2": read the scale from the currency, or from your reference data if internal rules differ (some markets quote with more decimals than the currency).

7. Splitting an amount to the cent

€100.00 split three ways gives 33.33 × 3 = €99.99: a cent has vanished. The classic method hands out the remainder one unit at a time:

/** Splits a positive amount into equal parts; the parts always add up to the total. */
static List<BigDecimal> split(BigDecimal total, int parts, Currency currency) {
    int scale = currency.getDefaultFractionDigits();
    BigDecimal unit = BigDecimal.ONE.movePointLeft(scale);             // 0.01 for the euro
    BigDecimal base = total.divide(BigDecimal.valueOf(parts), scale, RoundingMode.DOWN);
    BigDecimal rest = total.subtract(base.multiply(BigDecimal.valueOf(parts)));
    int extraUnits = rest.divide(unit).intValueExact();                // cents left over
    List<BigDecimal> result = new ArrayList<>(parts);
    for (int i = 0; i < parts; i++) {
        result.add(i < extraUnits ? base.add(unit) : base);
    }
    return result;                                                     // [33.34, 33.33, 33.33]
}

The same principle applies to allocating fees pro rata across a portfolio: compute the rounded shares, then assign the difference to the largest line, following a written and tested rule.

8. A real Money type with JSR 354

A BigDecimal alone does not say which currency it is in. The Money and Currency API (JSR 354, javax.money) and its reference implementation Moneta (org.javamoney:moneta) pair the two and refuse to add euros to dollars:

MonetaryAmount price = Money.of(new BigDecimal("1234.56"), "EUR");
MonetaryAmount fees = Money.of(new BigDecimal("10"), "EUR");
MonetaryAmount total = price.add(fees);                     // EUR 1244.56
price.add(Money.of(5, "USD"));                              // MonetaryException: currency mismatch

MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.UK);
format.format(total);                                       // the amount formatted for the UK locale

Moneta can also convert using rates published online, but in a bank the rates come from your reference data: plug in your own rate provider rather than an implicit network call. If you would rather avoid the dependency, a simple record Amount(BigDecimal value, Currency currency) with its checks already gives you the essentials.

9. Storing and exchanging

Key points

Going further: value dates and interest day counts in our tutorial on business days and conventions with Strata.

Doubles in your calculations?

Our legacy diagnostic finds fragile calculations, end-of-support versions and technical debt in your applications, and tells you what to fix first.

The diagnostic All tutorials

Worth a look