RangeError: precision is out of range
當傳遞給 toExponential、toFixed 或 toPrecision 的數字超出允許範圍時,會發生 JavaScript 異常 "precision is out of range"。
訊息
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)
錯誤型別
RangeError
哪裡出錯了?
這些方法中的一個精度引數超出範圍。
Number.prototype.toExponential(),要求引數在 0 到 100(含)之間。Number.prototype.toFixed(),要求引數在 0 到 100(含)之間。Number.prototype.toPrecision(),要求引數在 1 到 100(含)之間。
示例
無效案例
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
有效情況
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