JavaScript RangeError精度超出范围

JavaScript RangeError精度超出范围

这个JavaScript异常 precision is out of range 是指当在 toFixed()toPrecision()toExponential() 方法中传入超出0到20(或21)范围的数字时出现的。

错误信息:

RangeError: The number of fractional digits is out of range (Edge) 
RangeError: The precision is out of range (Edge) 
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

发生了什么

其中一个方法(toExponential(),toFixed()和toPrecision())中的精度参数超出了范围。

示例1: 在这个例子中,RangeError发生在-100和toFixed()被传递的时候。

function Geeks() {
    try {
        3.54.toFixed(-100);
 
        console.log("'Precision out of range'"
            + " error has not occurred");
    } catch (e) {
        console.log("'Precision out of range'"
            + " error has occurred");
    }
}
 
Geeks();

输出:

'Precision out of range' error has occurred

示例2: 在这个示例中,传递给toExponential()的参数是-4,因此发生了RangeError。

function Geeks() {
    try {
        77.1234.toExponential(-4);
 
        console.log("'Precision out of range'"
            + " error has not occurred");
    } catch (e) {
        console.log("'Precision out of range'"
            + " error has occurred");
    }
} 
 
Geeks();

输出:

'Precision out of range' error has occurred

示例 3: 在这个例子中,RangeError 错误发生在将 -1 传递给 toPrecision() 函数时。

function Geeks() {
    try {
        5643.9.toPrecision(-1);
 
        console.log("'Precision out of range'"
            + " error has not occurred");
    } catch (e) {
        console.log("'Precision out of range'"
            + " error has occurred");
    }
} 
 
Geeks();

输出:

'Precision out of range' error has occurred

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程