5

Chrome 29.0.1547.57:

0.0095 .toFixed(3) // "0.009"
0.1095 .toFixed(3) // "0.110"
1.1095 .toFixed(3) // "1.109"

What's wrong with this function?
I know that I can write my own function, the question here is why stock function is so buggy? According to MDN it was implemented in JS 1.5 so it's not new. Or maybe I don't understand this function right?

mpx5
  • 51
  • 1
  • 4
  • Buggy may not be the most appropriate word to describe how `toFixed` works, it's just how floating pointer numbers work, which might not be expected. – chridam Aug 22 '13 at 08:13
  • http://stackoverflow.com/questions/12105787/tofixed-javascript-function-giving-strange-results – user700284 Aug 22 '13 at 08:14
  • 2
    If you thinking floating point numbers and *rounding* is buggy, wait till you deal with code that mixes floating point numbers and financial transactions. – Jeremy J Starcher Aug 22 '13 at 08:17

1 Answers1

6

The problem is that binary floating point representation of most decimal fractions is not exact. The internal representation of 0.0095 may actually be something like 0.00949999, so toFixed rounds down, while 0.1095 might be 0.109500001, which rounds up.

See Javascript toFixed Not Rounding

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612