0

Why does toFixed() not work as expected for the following case? What is the solution?

Code:

var num = 5.56789;
var n = num.toFixed(16);
console.log(num)
console.log(n)

Expected value of n: 5.5678900000000000

Actual value of n: 5.5678900000000002

Note:

  1. I have gone through all the relevant stack overflow questions.
  2. I understand it's not giving the expected results because floating-point numbers cannot be represented perfectly in binary.
  3. What I am expecting is a library function that actually acknowledges the above and generates the expected output.
Syntle
  • 5,168
  • 3
  • 13
  • 34
Aadarsh
  • 41
  • 6
  • 4
    You are getting this precisely for the reason that floating point numbers are not exact. The only real way you could get this to work as you expect would be if you discarded the floating point entirely. This isn't a problem with JS or the toFixed function, it's a limitation of floating point numbers – Dan Jun 16 '20 at 12:53
  • 1
    There are solutions listed on [this page](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) for rounding or truncating. You can also look into the `bigfloat` library. – kmoser Jun 16 '20 at 13:38

1 Answers1

5

You've pretty much answered your own question, javascript Number class is a 64 bit floating point value, and the numbers you are talking about go beyond the precision allowed by the given 64 bits. In order to get around this limitation a library like https://github.com/munrocket/double.js will get you up to 128 bits of precision.

Francois du Plessis
  • 2,143
  • 2
  • 17
  • 17