JavaScript Number toPrecision() 方法用于检索表示指定精度的此数字的字符串,或者将输入数字格式化为指定精度。Precision 描述用于表示值的位数。
如果 precision' 参数的值不在 [0, 100] 范围内,则会引发 RangeError 异常。如果未为此方法指定 'precision' 参数值,则返回相同的输出。
注意:如果精度值大于总位数,则会在数字末尾添加额外的零。
语法
以下是 JavaScript Number toPrecision() 方法的语法 -
toPrecision(precision)
参数
此方法采用一个名为 'precision' 的可选参数,下面将解释 -
- precision (可选) − 指定有效位数的整数。
返回值
此方法返回指定精度的 formetted 数字。
示例 1
JavaScript number toPrecision() 方法将数字格式化为指定的精度或长度。如果省略 precision 值,则按原样返回数字。
<html>
<head>
<title>JavaScript toPrecision() Method</title>
</head>
<body>
<script>
const val = 10.34543;
document.write("Given value = ", val);
document.write("<br>Result = ", val.toPrecision());
</script>
</body>
</html>
输出
上面的程序在输出中返回 “10.34543” -
Given value = 10.34543
Result = 10.34543
Result = 10.34543
示例 2
如果向 Number toPrecision() 方法传递了 'precision' 参数值,则该方法会将输入值格式化为指定的精度。
<html>
<head>
<title>JavaScript toPrecision() Method</title>
</head>
<body>
<script>
const val = 123.3454;
const p1 = 3;
const p2 = 5;
const p3 = 12;
document.write("Given value = ", val);
document.write("<br>Precision values are = ", p1, ", ", p2, " and ", p3);
document.write("<br>Formatted result1 = ", val.toPrecision(p1));
document.write("<br>Formatted result2 = ", val.toPrecision(p2));
document.write("<br>Formatted result3 = ", val.toPrecision(p3));
</script>
</body>
</html>
输出
上述程序根据指定的精度格式化 input 值。
Given value = 123.3454
Precision values are = 3, 5 and 12
Formatted result1 = 123
Formatted result2 = 123.35
Formatted result3 = 123.345400000
Precision values are = 3, 5 and 12
Formatted result1 = 123
Formatted result2 = 123.35
Formatted result3 = 123.345400000
示例 3
如果可选参数 'precision' 的值不在 [1, 100] 范围内,则此方法会引发 'RangeError' 异常。
<html>
<head>
<title>JavaScript toPrecision() Method</title>
</head>
<body>
<script>
const val = 123;
const precision = 101;
document.write("Given value = ", val);
document.write("<br>Precision value = ", precision);
try {
document.write("<br>Result = ", val.toPrecision(precision));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
上述程序将 'RangeError' 异常抛出为 −
Given value = 123
Precision value = 101
RangeError: toPrecision() argument must be between 1 and 100
Precision value = 101
RangeError: toPrecision() argument must be between 1 and 100