Five simple utilities for comparing two floating point numbers, each with a short alias:
equal
oreq
,lessThan
orlt
,lessThanOrEqual
orlte
,greaterThan
orgt
, andgreaterThanOrEqual
orgte
.
The default epsilon is 1e-6
and can be customized using the third parameter.
a, b |
eq(a, b) |
lt(a, b) |
lte(a, b) |
gt(a, b) |
gte(a, b) |
---|---|---|---|---|---|
1, 2 |
✅ | ✅ | |||
1, 1 + 1e-5 |
✅ | ✅ | |||
1, 1 + 1e-7 |
✅ | ✅ | ✅ | ||
1, 1 |
✅ | ✅ | ✅ | ||
1 + 1e-7, 1 |
✅ | ✅ | ✅ | ||
1 + 1e-5, 1 |
✅ | ✅ | |||
2, 1 |
✅ | ✅ |
The above table is assuming the default epsilon of 1e-6
.
$ npm i epsicheck
import { eq } from 'epsicheck'
console.assert(eq(0.1 + 0.2, 0.3))
console.assert(0.1 + 0.2 != 0.3)