C# Reference ยท Numbers and Math
Comparing floating-point values in C#
How to compare double and float values in C#: why == fails, absolute and relative tolerances, NaN rules, Epsilon pitfalls and when to use decimal.
float and double store numbers in binary. Most decimal fractions, such as 0.1, have no exact binary form, so the stored value is the nearest one that fits. Arithmetic then adds tiny rounding errors, and two calculations that are equal on paper often differ in the last bit. That is why 0.1 + 0.2 == 0.3 is false.
The fix is to decide what "equal enough" means for your data and compare with a tolerance. This page shows the options: absolute and relative tolerance, comparing by units in the last place, handling NaN and infinity, and avoiding the problem with decimal or integers.
bool exact = 0.1 + 0.2 == 0.3; // false bool close = Math.Abs((0.1 + 0.2) - 0.3) < 1e-9; // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
bool Math.Abs(x - y) <= tolerance // absolute bool Math.Abs(x - y) <= relative * Math.Max(Math.Abs(x), Math.Abs(y)) // relative static bool double.IsNaN(double d) static bool double.IsFinite(double d) static bool double.IsInfinity(double d) static double Math.BitIncrement(double x) static double Math.BitDecrement(double x) static double Math.ScaleB(double x, int n) public const double double.Epsilon // smallest positive subnormal value (about 4.94e-324)
| Approach | Use when |
|---|---|
Exact == |
The values are copied, assigned constants, or results of exact operations on small integers. |
| Absolute tolerance | Values have a known scale, such as coordinates in meters. |
| Relative tolerance | Values can be large or small, such as scientific data. |
| Tolerance plus a tiny absolute floor | Values may be close to zero, where a relative test never succeeds. |
decimal or integers |
Money and counts that must be exact in base 10. |
Errors: none. Comparisons with NaN simply return false (and != returns true).
Usage notes
double.Epsilonis not machine epsilon. It is the smallest positive subnormal number (about 4.94e-324), far smaller than the rounding error of ordinary values. For the gap next to 1.0 useMath.BitIncrement(1.0) - 1.0, which is about 2.2e-16.- Choose the tolerance from your problem. 1e-9 suits many
doublecalculations, 1e-5 or 1e-6 suitsfloat. After long chains of operations the errors accumulate, so allow more. - Near zero, use both.
Math.Abs(x - y) <= Math.Max(absTol, relTol * scale). Otherwise numbers that should be zero and1e-17look "very different" in relative terms. NaNbreaks sorting and dictionaries if you ignore it.==saysNaN != NaN, butEquals,CompareToandArray.Sorttreat it as a regular value that sorts first. FilterNaNout of data before comparing.- Do not use floating-point loop counters (
for (double x = 0; x != 1; x += 0.1)). The loop may never hit the target exactly. Count with an integer and computex = i * 0.1. floataccumulates error faster. It has about 7 digits of precision, against about 15 to 17 fordouble. Mixingfloatanddoublein a comparison widens thefloatfirst, and its rounding error then shows.- Equality in tests. Test frameworks have an approximate comparison (such as a precision argument on a floating-point assertion). Use it rather than
==. decimalis not a cure for everything. It is exact for decimal fractions, but1m / 3m * 3mis0.9999999999999999999999999999. Round money at defined points.