Java tutorial · Intermediate · 15 min
Rounding errors and floating point in Java: what finance needs to know
A one-cent difference on a statement, a reconciliation that does not match, a price that changes depending on the server: in finance, rounding errors are not a technical detail, they show up in the accounts and at the supervisor. This tutorial explains where they come from and how to control them, with the JDK and Apache Commons Math.
Tested source code, free to use: GitHub, Scopas-Team/java-finance-tutorials (Apache 2.0 licence)
1. How a double represents a number
A double follows the IEEE 754 standard: a sign, an exponent and a 52-bit mantissa, giving 15 to 17 significant decimal digits. The number is stored in base 2: 0.5 or 0.25 are exact, but 0.1, 0.2 or 2.675 are not. The double keeps the nearest binary value.
new BigDecimal(2.675); // 2.67499999999999982236431605997495353221893310546875
Math.ulp(1.0); // 2.220446049250313E-16: the gap between 1.0 and the next double
Math.ulp(1_000_000.0); // 1.1641532182693481E-10: the gap grows with the number
Precision is relative: around one million, two neighbouring doubles are about 10-10 apart. On an outstanding of a trillion, the gap already exceeds a hundredth of a cent.
2. The trap of rounding a double
double x = 1.005;
Math.round(x * 100) / 100.0; // 1.0: x * 100 is 100.49999999999999
new BigDecimal(x).setScale(2, RoundingMode.HALF_UP); // 1.00: the binary value is below 1.005
BigDecimal.valueOf(x).setScale(2, RoundingMode.HALF_UP); // 1.01: goes through the string "1.005"
Precision.round(x, 2); // 1.01: Commons Math, same principle
Three methods, two results. The one the client expects is 1.01. The lesson: an amount must never be a double to be rounded; if one comes from a model output, go through BigDecimal.valueOf or Precision.round, never Math.round(x * 100) / 100.0.
3. Error accumulation
double sum = 0.0;
for (int i = 0; i < 10_000_000; i++) {
sum += 0.1;
}
System.out.println(sum); // 999999.9998389754, not 1000000.0
Each addition rounds to the nearest double, and the errors add up. Two remedies for calculations in double:
// Compensated (Kahan) summation: keeps the part lost on each addition
static double kahanSum(double[] values) {
double sum = 0.0, compensation = 0.0;
for (double v : values) {
double y = v - compensation;
double t = sum + y;
compensation = (t - sum) - y;
sum = t;
}
return sum;
}
// The JDK already does it: DoubleStream.sum() uses compensated summation
double total = Arrays.stream(values).sum();
For amounts, the real answer is still BigDecimal or integer cents: addition is exact there.
4. Catastrophic cancellation
Subtracting two very close numbers wipes out the common significant digits and leaves only the error:
double a = 1.0 + 1e-15;
double b = 1.0;
System.out.println(a - b); // 1.1102230246251565E-15 instead of 1.0E-15: an 11% error
In finance, the typical case is a sensitivity computed by finite difference (price with a bump minus price without), or a gap between two large outstandings. Choose a suitable bump size, rearrange the formula to avoid the subtraction, or compute the difference directly when the model allows it.
5. Double rounding
Rounding in two steps does not give the same result as rounding once:
BigDecimal v = new BigDecimal("1.2345");
v.setScale(2, RoundingMode.HALF_UP); // 1.23
v.setScale(3, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP); // 1.24
The real-life case: a rate rounded to three decimals in one system, then the amount rounded to the cent in another. Find every rounding step in the chain and keep only one, where the business rule says it belongs.
6. Round each line or the total?
Interest computed day by day and rounded each day does not add up to the same total as interest rounded once at the end of the period. Neither method is "right" in the abstract: the contract, market convention or regulation decides. When the euro was introduced, for example, Regulation (EC) 1103/97 set conversion rates to six significant figures, forbade rounding them and required converted amounts to be rounded to the nearest cent. Write the rule down, code it in one place and test it.
7. Comparing doubles: always with a tolerance
0.1 + 0.2 == 0.3; // false
Precision.equals(0.1 + 0.2, 0.3, 1e-12); // true: absolute tolerance
Precision.equals(0.1 + 0.2, 0.3, 1); // true: at most 1 ulp apart
Precision.compareTo(priceA, priceB, 1e-9); // 0 if equal within the tolerance
In tests, AssertJ does the same: assertThat(price).isCloseTo(10.4506, within(1e-4)). Choose a tolerance with a business meaning (a tenth of a basis point on a rate, a cent on a price), not a random value.
8. Apache Commons Math in the toolbox
build.gradle
dependencies {
implementation 'org.apache.commons:commons-math3:3.6.1'
}
commons-math3 is stable and widely used; its successors are split into Apache Commons Numbers, Statistics and RNG. The parts most useful in finance:
Precision: tolerance comparisons and reliable rounding of adouble.MathArrays.linearCombination: a dot product computed with extra precision, useful for a portfolio value (quantities × prices).DescriptiveStatistics: mean, standard deviation, percentiles; for example a historical VaR.- Solvers (
BrentSolver) for a yield or an implied volatility, and interpolators for curves.
// Portfolio value: sum of quantities × prices, in extended precision
double value = MathArrays.linearCombination(quantities, prices);
// 99% historical VaR over a series of daily losses
DescriptiveStatistics stats = new DescriptiveStatistics(losses);
double var99 = stats.getPercentile(99);
// Internal rate of return of a cash-flow series: the root of the NPV
UnivariateFunction npv = rate -> netPresentValue(flows, rate);
double irr = new BrentSolver(1e-10).solve(100, npv, -0.99, 1.0);
9. Reproducible results
Since Java 17 (JEP 306), basic operations on doubles give the same result on every platform. The Math functions (exp, log, pow), however, may differ by one ulp depending on the processor or JVM. For a calculation that must be replayed identically (audit, supervisory check, production versus test comparison), use StrictMath, and keep the order of operations fixed: a parallel calculation that adds in a different order does not give exactly the same total.
Key points
- Amounts in
BigDecimalor cents;doublefor models and statistics - Never
Math.round(x * 100) / 100.0: useBigDecimal.valueOforPrecision.round - Compensated summation for large sums of
doubles - Beware of subtracting close numbers
- One rounding per calculation chain, in the right place
- Comparisons with a tolerance that has a business meaning
StrictMathand a fixed order of operations when results must be replayed identically
Try your own numbers with the tool what a double really stores.
For the basics: our tutorial on handling money in Java.
Unexplained differences in your calculations?
Our legacy diagnostic finds fragile calculations and misplaced rounding in your applications, and tells you what to fix first.