-2

When I do, for example, 14 * 0.2, I get 2.8000000000000003 instead of 2.8.
Why does it do this, and how can I fix it?

According to this page, Strings automatically cut trailing 0s off, so I tried

var foo = 14 * 0.2;
console.log(foo.toFixed(3).toString());

but it still comes back with trailing 0s (2.800).

Community
  • 1
  • 1
Joseph Webber
  • 2,010
  • 1
  • 19
  • 38
  • this is not an error, it is how floating point math works. see http://stackoverflow.com/questions/588004/is-floating-point-math-broken. Also, `toString()` doesn't truncate, it strips insignificant 0s (trailing 0s that run to infinity, which this number does not do). – Claies Jul 28 '14 at 03:10
  • This is like asking why `0.1 + 0.2` isn't `0.3`. – Derek 朕會功夫 Jul 28 '14 at 03:19
  • Sorry for posting a duplicate post, I couldn't find anything related to my problem in the related posts and didn't know the exact terminology to find the answer on my own. Thanks to everyone for their help, and I don't mind getting down-voted if I come out smarter in the end. – Joseph Webber Jul 28 '14 at 03:34

2 Answers2

1

I don't think String will cut trailing 0s, But if you will convert that in number then it will ignore trailing 0s after decimal point.

var foo = 14 * 0.2;
console.log(+foo.toFixed(3));
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

Your call of toFixed function will return the String, not a some kind of a number. And this String representation is specifically mentioned in the documentation to have trailing zeros. The next call to toString simply does nothing.

ForNeVeR
  • 6,726
  • 5
  • 24
  • 43