Floating-point precision
Floating-point numbers represent many decimals approximately rather than exactly.
How it works
Many decimals are finite on paper and repeat forever when expressed in binary. A finite representation rounds that repeating value, so adding several approximations can expose a tiny difference. If the answer has to be an exact amount, choose the representation before doing the arithmetic.
Walk through an example
The decimal 0.1 does not have a finite binary fraction. Adding approximations can leave a result just above or below the decimal you expect.
What to watch for
For money, use integer minor units or a decimal type when exact decimal arithmetic is required. For measurements, choose a tolerance that matches the problem.
Check your understanding
What integer can represent their exact combined price?
See the example and explanation
- Worked example
- Given
Two prices are represented as 10 cents and 20 cents. - Answer
30 cents.
Adding whole cents gives an exact integer result without a decimal rounding step.