C/C++ Arena

Step 6 of 7

Floating-point rounding

double stores numbers in binary, and most decimal fractions (like 0.1) have no exact binary form. So:

0.1 + 0.2 == 0.3    // false! 0.30000000000000004 vs 0.29999999999999998

Two rules professionals follow:

  1. Never compare doubles with == after arithmetic. Check they're close enough, relative to their size.
  2. Never store money in double. Store integer cents (int64_t), and only format as dollars for display.

A good closeness test scales the tolerance with the numbers:

|a - b| <= eps * max(1, |a|, |b|)

Your turn: write int nearly_equal(double a, double b, double eps) using that formula. Don't use <math.h>; write the absolute value yourself.

Previous: The signed/unsigned comparison trap Next: Challenge: hunt the undefined behavior