范围错误:精度超出范围

当将 0 到 20(或 21)范围之外的数字传递给 toFixedtoPrecision 时,会发生 JavaScript 异常 "精度超出范围"。

¥The JavaScript exception "precision is out of range" occurs when a number that's outside of the range of 0 and 20 (or 21) was passed into toFixed or toPrecision.

信息

¥Message

RangeError: toExponential() argument must be between 0 and 100 (V8-based & Safari)
RangeError: toFixed() digits argument must be between 0 and 100 (V8-based & Safari)
RangeError: toPrecision() argument must be between 1 and 100 (V8-based & Safari)
RangeError: precision -1 out of range (Firefox)

错误类型

¥Error type

RangeError

什么地方出了错?

¥What went wrong?

其中一种方法存在超出范围的精度参数:

¥There was an out of range precision argument in one of these methods:

示例

¥Examples

无效案例

¥Invalid cases

js
(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

有效案例

¥Valid cases

js
(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

也可以看看