How to make this simple operation return true?

Asked

Viewed 67 times

0

I saw a post and was confused: 0.2 + 0.4 == 0.6 returned false. How to make this sum operation really equal to 0.6?

  • 1

    This is due to the fact that such numbers when represented in the binary form of floating point do not give an exact value but periodic tithes, which makes the sum not exactly equal. The types of float and double data are inherently inaccurate and should only be used if their application can live with such inaccuracies. A possible way of circumventing, in addition to employing another type of data, is to use rounding functions.

  • Better consult the links of duplicate questions. Here is full of incorrect or superficial information.

  • @anonimo is precisely the periodic tithes that cannot be represented in the floating point, being limited to the size used and, therefore, will always be truncated, changing the value represented. I believe you got confused in your comment.

1 answer

3


It is returned false because of the floating point. Javascript uses a 64-bit floating point representation, it basically gives you an approximate value, so:

To 0.1 in the format pattern binary64, the representation would be:

  • 0.1000000000000000055511151231257827021181583404541015625 decimally

Then the constants 0.2 and 0.4 in your program, are approximate values. The sum of 0.2 and 0.4 ends up being larger than the rational number 0.6 and therefore disagrees with the constant in its code.

  • 1

    Your explanation is very good, what would be the proposal to solve this equality operation? toFixed?

  • 1

    toFixed() It’s a good way to fix it, I’d do it this way: (0.2 + 0.4).toFixed(1) == 0.6

Browser other questions tagged

You are not signed in. Login or sign up in order to post.