DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Do you ever need to equally compare numbers (floating points)?

I have long known of the existence of -- well, I don't care of bad precision in computerized floating points...

But I have never tried this,

0.1 + 0.2 == 0.3
0.1 + 0.2 - 0.3 == 0.0
0.1 == 0.1 + 1e-26
Enter fullscreen mode Exit fullscreen mode

Now, I know that floating point equality is broken in most programming languages. (I believe Lisp family are exceptions, if you use Fractions).

So, do you ever need to equally compare floating points? If so, what language do you use? And, do you need to write a comparison function, or is there a library for it?

This might be a such comparator,

function eq (a, b, precision = Number.EPSILON) {
  const i = (n) => Math.round(n / precision)
  return i(a - b + 1) === i(1)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

mateuszjarzyna profile image
Mateusz Jarzyna

If you have to compare two numbers you should use some epsilon (depends on your needs).
But there are some cases where you should not use float numbers - for example money.

BTW, there is the simplest way to write the comparator abs(a - b) <= epsilon.