JavaScript Number toPrecision() 方法
JavaScript Number toPrecision() 方法用于检索以指定精度表示该数字的字符串,或者将输入数字格式化为指定精度。精度描述了用于表达数值的位数。
如果"precision"参数的值不在 [0, 100] 范围内,则会抛出"RangeError"异常。如果此方法未指定"precision"参数值,则返回相同的输出。
注意:如果 precision 值大于数字的总位数,则会在数字末尾添加额外的零。
语法
以下是 JavaScript Number toPrecision() 方法的语法 -
toPrecision(precision)
参数
此方法接受一个名为"precision"的可选参数,其解释如下 -
- precision(可选) - 一个指定有效数字位数的整数。
返回值
此方法返回一个格式化的数字指定的精度。
示例 1
JavaScript 数字 toPrecision() 方法将数字格式化为指定的精度或长度。如果省略精度值,则按原样返回数字。
<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
示例 2
如果传递了 'precision' 参数值,Number toPrecision() 方法会将输入值格式化为指定的精度。
<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>
输出
上述程序根据指定的精度格式化输入值。
Given value = 123.3454 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

