'Why does toFixed() only take 0 - 20 digits

In the javascript docs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

toFixed() only takes 0 - 20 so

123.1234567294239482379483749.toFixed(20)

is

"123.12345672942394969596"

and results in a range error

123.1234567294239482379483749.toFixed(21)
RangeError: toFixed() digits argument must be between 0 and 20

Thanks



Solution 1:[1]

From the ECMA document here, toFixed is specified as

Note point number 2, this is the reason for the range

15.7.4.5 Number.prototype.toFixed (fractionDigits)
Return a string containing the number represented in fixed-point notation with fractionDigits digits
after the decimal point. If fractionDigits is undefined, 0 is assumed. Specifically, perform the
following steps:
1. Let f be ToInteger(fractionDigits). (If fractionDigits is undefined, this step produces the value
0).
2. If f < 0 or f > 20, throw a RangeError exception.
3. Let x be this number value.
4. If x is NaN, return the string "NaN".
5. Let s be the empty string.
6. If x ? 0, go to step 9.
7. Let s be "-".
8. Let x = –x.
9. If x ? 1021, let m = ToString(x) and go to step 20.
10. Let n be an integer for which the exact mathematical value of n ÷ 10f – x is as close to zero as
possible. If there are two such n, pick the larger n.
11. If n = 0, let m be the string "0". Otherwise, let m be the string consisting of the digits of the
decimal representation of n (in order, with no leading zeroes).
12. If f = 0, go to step 20.
13. Let k be the number of characters in m.
14. If k > f, go to step 18.
15. Let z be the string consisting of f+1–k occurrences of the character ‘0’.
16. Let m be the concatenation of strings z and m.
17. Let k = f + 1.
18. Let a be the first k–f characters of m, and let b be the remaining f characters of m.
19. Let m be the concatenation of the three strings a, ".", and b.
20. Return the concatenation of the strings s and m.

Solution 2:[2]

March 2022

This no longer gives an error if the number of rounding places is more than 20 digits.

This limit now is 100 places See here on MDN.

RangeError:

If digits is too small or too large. Values between 0 and 100, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as chosen.

Examples here (this does not mean that the rounding is correct as it only copes with rounding to 20 places, but does not give an error if the required number of places is more than 20).

The error given for decimal places above 100 is:

Error: toFixed() digits argument must be between 0 and 100

console.log(123.1234567294239482379483749.toFixed(20));
console.log(123.1234567294239482379483749.toFixed(30));
console.log(123.1234567294239482379483749.toFixed(100));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Tanwar
Solution 2