2

I typed in the console :

var number = .14 
number.toFixed(2)
"0.14"
number.toFixed(2)*100
14.000000000000002

This only happens to .14, but not other values. Like .16 works fine. Anyone knows what is going on underneath the hood ? Super weird.

Seen in the comments, if I would like to get trim off/round the result, what should I do if not using toFixed(2)?

sammiwei
  • 3,140
  • 9
  • 41
  • 53
  • 2
    Floating point numbers are approximations. `14/100` can't be represented exactly in binary, just as `1/3` can't be represented exactly in decimal. – Barmar Jul 01 '13 at 19:13
  • To be perfectly clear about the duplicate: `"0.14"` is coerced to a number for the multiplication (not covered by the duplicate, but hopefully fairly obvious), and the result is subject to floating point error (covered by the duplicate). – apsillers Jul 01 '13 at 19:14
  • Look into the IEEE-754 floating-point format. It stores numbers as fixed-precision values (in base 2) with an exponent component (the floating-point part). Basically, not all numbers are representable exactly. – Cameron Jul 01 '13 at 19:15
  • To respond to your edit: use `toFixed` on the *result* (e.g., `(number.toFixed(2)*100).toFixed(2)`). You truncated one of your multiplication terms, but the resultant product is not yet truncated. The output of the multiplication is subject to floating point error, even if the input terms are correct. – apsillers Jul 01 '13 at 19:20

0 Answers0