Errors: Precision range
Errors: Precision range
信息
RangeError: precision {0} out of range (Firefox)
RangeError: toExponential() argument must be between 0 and 20 (Chrome)
RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)
RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
错误类型
RangeError
哪里出错了?
其中一种方法有一个超出范围的精度参数:
Number.prototype.toExponential()
Number.prototype.toFixed()
Number.prototype.toPrecision()
这些方法的允许范围通常在0到20(或21)之间。ECMAScript规范允许扩展这个范围。
Method | Firefox (SpiderMonkey) | Chrome, Opera (V8) |
---|---|---|
Number.prototype.toExponential() | 0 to 100 | 0 to 20 |
Number.prototype.toFixed() | -20 to 100 | 0 to 20 |
Number.prototype.toPrecision() | 1 to 100 | 1 to 21 |
示例
无效的情况
77.1234.toExponential(-1 // RangeError
77.1234.toExponential(101 // RangeError
2.34.toFixed(-100 // RangeError
2.34.toFixed(1001 // RangeError
1234.5.toPrecision(-1 // RangeError
1234.5.toPrecision(101 // RangeError
有效的情况
77.1234.toExponential(4 // 7.7123e+1
77.1234.toExponential(2 // 7.71e+1
2.34.toFixed(1 // 2.3
2.35.toFixed(1 // 2.4 (note that it rounds up in this case)
5.123456.toPrecision(5 // 5.1235
5.123456.toPrecision(2 // 5.1
5.123456.toPrecision(1 // 5