Free tool · Dev corner
What a double really stores
Type an amount or a rate: the tool shows the exact value a Java double keeps in memory, what three ways of rounding it give, and the error that builds up when you add it thousands of times. JavaScript numbers are the same IEEE 754 doubles as Java's, so the results are your JVM's.
The calculation runs in your browser: nothing is sent or stored.
What the double stores
You entered . The nearest double is exactly:
This number is exact in binary: no difference from what you entered.
Difference from what you entered: . This is what new BigDecimal(x) returns.
Rounded to decimals
| Java code | Result |
|---|---|
Math.round(x * ) / x * = | |
new BigDecimal(x).setScale(n, HALF_UP) | |
BigDecimal.valueOf(x).setScale(n, HALF_UP) | |
BigDecimal.valueOf(x).setScale(n, HALF_EVEN) | |
Watch out: the first two lines round the binary value, not the number entered, and do not give what the client expects. Go through BigDecimal.valueOf.
Here the methods agree. Try 1.005, 2.675 or 0.285 to see naive rounding go wrong.
HALF_UP and HALF_EVEN (banker's rounding) differ here: the contract or market convention decides.
Added times
Sum in double | |
|---|---|
Exact sum (BigDecimal) | |
| Accumulated error | |
No error here: this number and its sums stay exact in binary.
Each addition rounds to the nearest double, and the errors add up. Compensated (Kahan) summation or BigDecimal avoids them.
Going further
- Rounding errors and floating point in Java: where these differences come from and how to control them, with Apache Commons Math.
- Handling money in Java:
BigDecimal, rounding and currencies. - The tutorials' tested code, free to use, is on GitHub.
Unexplained differences in your calculations?
Our legacy diagnostic finds fragile calculations and misplaced rounding in your applications.