Skip to content

Commit

Permalink
Correct explanation for the toFixed oddities.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcmonkey4eva committed Mar 9, 2018
1 parent 40ce068 commit c4f54e2
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1370,7 +1370,27 @@ Long story short, if `null` is less than `0` is `false`, then `null >= 0` is `tr

### 💡 Explanation:

View the Firefox source, `toFixed` method is to convert the value of the conversion, not the standard implementation.
While your first instinct may be that IE11 is correct and Firefox/Chrome are wrong, the reality is that Firefox/Chrome are more directly obeying standards for numbers (IEEE-754 Floating Point), while IE11 is minutely disobeying them in (what is probably) an effort to give clearer results.

You can see why this occurs with a few quick tests:

```js
// Confirm the odd result of rounding a 5 down
0.7875.toFixed(3) // -> 0.787
// It looks like it's just a 5 when you expand to the
// limits of 64-bit (double-precision) float accuracy
0.7875.toFixed(14) // -> 0.78750000000000
// But what if you go beyond the limit?
0.7875.toFixed(20) // -> 0.78749999999999997780
```

Floating point numbers are not stored as a list of decimal digits internally, but through a more complicated methodology that produces tiny inaccuracies that are usually rounded away by toString and similar calls, but are actually present internally.

In this case, that "5" on the end was actually an extremely tiny fraction below a true 5. Rounding it at any reasonable length will render it as a 5... but it is actually not a 5 internally.

IE11, however, will report the value input with only zeros appended to the end even in the toFixed(20) case, as it seems to be forcibly rounding the value to reduce the troubles from hardware limits.

See for reference `NOTE 2` on the ECMA-262 definition for `toFixed`.

* [**20.1.3.3** Number.prototype.toFixed (`fractionDigits`)](https://www.ecma-international.org/ecma-262//#sec-number.prototype.tofixed)

Expand Down

0 comments on commit c4f54e2

Please sign in to comment.