Round-Off Error
Why double values are sometimes slightly wrong, how those tiny errors show up in output and comparisons, how they accumulate, and how to write code that is not fooled by them.
Computers allot a specified amount of memory to store data based on its type. A double uses a fixed number of bits, so it can represent only a limited set of real numbers exactly. If an expression would evaluate to a double that is more precise than can be stored in the allotted memory, a round-off error occurs: the result is rounded to the nearest representable value. The errors are tiny, but they can make 0.1 + 0.2 print as 0.30000000000000004, make equality tests fail, and cause truncation to be off by one. To avoid the rounding errors that naturally occur, use int values when the quantity is really a whole number.
1A Fixed Amount of Memory
Every type has a fixed size. An int uses 4 bytes and represents every whole number in its range exactly. A double uses 8 bytes to represent real numbers across an enormous range, from tiny fractions to numbers with hundreds of digits. To cover that range with a fixed number of bits, a double stores about 15 to 17 significant digits and a position for the decimal point. Values that need more precision than that, or that cannot be written exactly in binary, must be rounded.
Round-off is therefore not a bug in Java; it is a property of storing real numbers in finite memory, and every programming language that uses this kind of number behaves the same way. The skill is to recognize when round-off can affect a result and to write code that does not depend on exact double values.
2Values That Cannot Be Stored Exactly
In decimal, one third is 0.333… with threes forever; any fixed number of digits is slightly too small. Computers store numbers in binary (base 2), where the same problem affects different fractions. Halves, quarters, and eighths are exact in binary, but one tenth is a repeating pattern, so 0.1, 0.2, 0.3, and most other decimal values with tenths or hundredths are stored as the closest value the double can hold.
Usually the difference is invisible, because Java prints the shortest decimal that identifies the stored value, so the literal 0.1 prints as 0.1. The difference becomes visible after arithmetic. Adding the stored versions of 0.1 and 0.2 produces a value that rounds to a different representable number than the stored 0.3, and Java prints it as 0.30000000000000004.
double can only hold certain values. Each calculation rounds to one of them, so two routes to "0.3" can end on neighboring values that print and compare differently.| Expression | Printed result | Why |
|---|---|---|
0.1 + 0.2 | 0.30000000000000004 | Neither value is exact in binary |
0.5 + 0.25 | 0.75 | Halves and quarters are exact in binary |
1.0 - 0.9 | 0.09999999999999998 | 0.9 is not exact |
0.29 * 100 | 28.999999999999996 | 0.29 is not exact |
3 * 10 + 5 (int) | 35 | Integer arithmetic within range is exact |
Why 0.1 + 0.2 Is Not 0.3
Predict the output.
System.out.println(0.1 + 0.2);
System.out.println(0.3);
System.out.println(0.5 + 0.25);
0.30000000000000004
0.3
0.75
- 1Line 1. Neither 0.1 nor 0.2 is stored exactly, and their sum is rounded to the nearest representable value, which is slightly above 0.3.
- 2Line 2. The literal 0.3 is stored as the representable value closest to 0.3, which Java prints as 0.3. It is a different
doublefrom the result on line 1. - 3Line 3. 0.5 and 0.25 are exact in binary (one half and one quarter), so their sum prints exactly.
0.30000000000000004, 0.3, and 0.75. Round-off depends on whether values can be represented exactly in binary.Round-off comes from representing real numbers in a fixed number of bits, and the same results appear in nearly every programming language. The fix is not to search for a broken line but to choose the right type (int for whole quantities) and to compare double values with a tolerance.
3Comparing double Values
The == operator compares stored values exactly. For computed double values, two results that should be mathematically equal can differ in their last bits, so == reports false. Code such as if (total == 1.0) can silently fail even though the total printed as nearly 1.
The safe pattern is to ask whether two values are close enough: compute the size of their difference with Math.abs(a - b) and compare it with a small tolerance, such as 0.000001. The tolerance should be far larger than any round-off error but far smaller than any difference that matters in the problem. Comparisons using < or > are usually less fragile than ==, but values near a boundary can still land on the wrong side.
Testing Closeness Instead of Equality
Compare 0.1 + 0.2 with 0.3, first with == and then by checking whether the difference is tiny.
double a = 0.1 + 0.2;
double b = 0.3;
System.out.println(a == b);
System.out.println(Math.abs(a - b) < 0.000001);
false
true
- 1Exact equality fails. The two values differ in their last bits.
- 2A tolerance test succeeds.
Math.abs(a - b)is the size of the difference, about 0.00000000000000006, which is far less than the chosen tolerance 0.000001. - 3Choosing the tolerance. Pick a tolerance much larger than round-off error but much smaller than any difference that matters for the problem.
== reports false, while the tolerance test reports true. When comparing computed double values, test whether they are close enough rather than exactly equal.0.1 + 0.2 == 0.3 is false. When a condition depends on two computed double values being equal, replace == with a tolerance check. Exact equality is reliable for int values, not for computed double values.
4Errors That Accumulate
A single round-off error is tiny, about one part in ten million billion. But each arithmetic step can add another tiny error, and long calculations, such as adding a small amount thousands of times, can let them accumulate into differences that appear in printed output or comparisons. Adding 0.1 ten times already produces 0.9999999999999999 instead of 1.0.
Accumulation matters most in programs that repeat the same double operation many times, such as simulations that add a time step over and over, or running totals of prices. Such programs should avoid exact comparisons and, when the underlying quantities are whole numbers, use int arithmetic instead.
| Additions of 0.1 | Running total (printed) | Equal to exact value? |
|---|---|---|
| 1 | 0.1 | prints like it |
| 2 | 0.2 | prints like it |
| 3 | 0.30000000000000004 | no |
| 10 | 0.9999999999999999 | no |
Adding 0.1 Ten Times
A program adds 0.1 to a total ten times. Predict the final total and whether it equals 1.0.
double total = 0.1 + 0.1 + 0.1 + 0.1 + 0.1
+ 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
System.out.println(total);
System.out.println(total == 1.0);
0.9999999999999999
false
- 1Each addition rounds. The tiny error in each step accumulates, as Figure 3 shows.
- 2The total prints 0.9999999999999999. It is extremely close to 1.0 but not equal.
- 3Equality fails.
==compares the exact stored values, so it reportsfalse.
0.9999999999999999, and total == 1.0 is false. Repeated double arithmetic accumulates round-off error.5Truncation Makes Round-Off Worse
Round-off interacts badly with casting. A result that should be exactly 29 may be stored as 28.999999999999996; casting it to int truncates the fraction and produces 28. The error is no longer tiny: it is off by a whole unit. This often surprises programmers converting prices to cents or percentages to counts.
The fix is to round instead of truncating whenever a double is supposed to represent a whole number: (int) (x + 0.5) for non-negative values. Rounding absorbs the tiny error in either direction, so 28.999999999999996 and 29.000000000000004 both become 29.
A Hidden Off-by-One
A program converts 0.29 dollars to cents with a cast. Predict the result.
double dollars = 0.29;
System.out.println(dollars * 100);
System.out.println((int) (dollars * 100));
System.out.println((int) (dollars * 100 + 0.5));
28.999999999999996
28
29
- 1The product. 0.29 × 100 is computed as 28.999999999999996, just below 29.
- 2Truncation. Casting drops the fraction, giving 28, a cent short.
- 3Rounding first. Adding 0.5 before casting gives 29, the intended value.
29. Never truncate a double that is supposed to be a whole number.When Adding 1 Changes Nothing
A double keeps only about 15 to 17 significant digits. Predict the output.
double huge = 10000000000000000.0;
System.out.println(huge);
System.out.println(huge + 1 == huge);
System.out.println(huge + 2 == huge);
1.0E16
true
false
- 1Printing. Very large
doublevalues print in scientific notation:1.0E16is 1016. - 2
huge + 1. At this size, neighboringdoublevalues are 2 apart, so adding 1 rounds back tohugeitself: the comparison istrue. - 3
huge + 2. Adding 2 reaches the next representable value, so the result differs.
(int) (0.29 * 100) is 28, not 29. Any time a computed double is converted to an int that should be exact, add 0.5 (for non-negative values) before casting, or better, keep the quantity as an int from the start.
6Using int Values to Avoid Rounding Errors
To avoid rounding errors that naturally occur, use int values. Integer arithmetic within the int range is exact: 10 + 10 + 10 is always 30. Many quantities that look like decimals are really counts of a smaller unit. Money is a count of cents; a duration in seconds can be a count of milliseconds; a measurement in meters with millimeter precision can be a count of millimeters. Storing these as int values and converting to a decimal display only when printing keeps every calculation exact.
double remains the right choice for genuinely continuous quantities, such as physical measurements, averages, and scientific calculations, where tiny relative errors do not matter. The important thing is to choose deliberately and, when using double, to compare with tolerances and round before converting to integers.
double values, use int values: count money in whole cents and convert to dollars only for display.| Situation | Risk | Safer approach |
|---|---|---|
| Comparing two computed doubles with == | False even when "equal" | Check Math.abs(a - b) < tolerance |
| Casting a computed double to int | Off by one after truncation | Round first: (int) (x + 0.5) |
| Money totals | Fractions of a cent appear | Store whole cents in an int |
| Adding many small doubles | Error accumulates | Use integers when values are naturally whole, or allow a tolerance |
Keeping Money Exact With Cents
Three items cost 10 cents each. Compute the total in two ways.
double priceDollars = 0.10;
double totalDollars = priceDollars + priceDollars + priceDollars;
System.out.println(totalDollars);
int priceCents = 10;
int totalCents = priceCents + priceCents + priceCents;
System.out.println(totalCents);
System.out.println(totalCents / 100 + "." + totalCents % 100 / 10 + totalCents % 10);
0.30000000000000004
30
0.30
- 1Dollars as doubles. The sum shows round-off: 0.30000000000000004.
- 2Cents as ints. Integer addition is exact: 30.
- 3Display only at the end. Integer division and remainder split 30 cents into dollars (0), dimes digit (3), and cents digit (0) to print "0.30" without any
doublearithmetic.
int keeps totals exact; convert to a dollars-and-cents string only for output.Prices such as 4.99 look like double values, but repeated additions of dollar amounts drift by fractions of a cent, and truncating can lose a whole cent. Programs that must balance exactly, like a store's register, count money in whole cents with int values.
Four Habits for Avoiding Round-Off Problems
1. Expect Tiny Errors
Most decimal fractions are stored as close approximations.
2. Compare With a Tolerance
Use Math.abs(a - b) < small value instead of ==.
3. Round Before Casting
Never truncate a double that should be a whole number.
4. Count Whole Units in ints
Cents, milliseconds, and millimeters keep arithmetic exact.
Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs, and the result is rounded to the representable value. Round-off makes some results print with extra digits, makes exact comparisons of computed double values unreliable, accumulates over repeated operations, and can make truncation off by one. To avoid rounding errors that naturally occur, use int values.