# How to correctly compare floating point numbers for equality

###
Benjamin Black
*Updated on *
・1 min read

IEEE 754 is an approximate representation of floating-point numbers; therefore, floating-point numbers should not be directly compared for equality.

(This issue is common to any language that uses IEEE 754 floating-point, including Javascript.)

Programmers are probably familiar with variations of this head-scratcher:

```
let f1 = 0.1 + 0.2;
let f2 = 0.3;
console.log(f1 === f2); // 'false'
```

Comparisons of IEEE 754 floating-point numbers must account for ε (epsilon), the maximum relative error in floating point numbers (defined as "the difference between 1 and the smallest floating-point number greater than 1").

In Javascript, the value of ε for IEEE 754 double-precision floating point is a static property on the `Number`

object (`Number.EPSILON`

).

To account for ε and correctly compare two floating-point numbers for equality, subtract one number from the other and ensure the difference is smaller than ε.

```
let f1 = 0.1 + 0.2;
let f2 = 0.3;
console.log(Math.abs(f1 - f2) < Number.EPSILON); // 'true'
```

(The comparison should be strict less-than, not lte, by the definition of ε: `1.0 + ε ≠ 1.0`

in IEEE 754 representation.)

**Addendum:** There is a stage 0 proposal to add a decimal numbers to Javascript, which can precisely represent all decimal numbers within its range and precision.

The "correct" way would be for ECMA group to abstract this gotcha into an override of the == and/or === operators for floats in an upcoming version of ES :D... but good tip!

That would certainly be breaking.

I feel like I wouldn't mind them doing that to

`==`

, which means "approximately equal" in my head, but in reality that would become a reason to use`==`

with all its coercions and we definitely don't need that.Nice! This problem is common for most of the languages, thanks for the reminder!

I'm new to js, and thus far have not seen the epsilon defined in any other languages. I recall in school calculating machine epsilon as an exercise. The only other time I've dealt with comparing floats we had to define our own acceptable epsilon. Is this very handy definition something that any other languages have implemented?

They sure do. C defines the values of ε for float, double, and long double floating point types in the standard header

`float.h`

as the constants`FLT_EPSILON`

,`DBL_EPSILON`

, and`LDBL_EPSILON`

.Awesome, thanks!