JavaScript Number toPrecision() 方法



JavaScript Number 的toPrecision()方法用於檢索表示此數字的指定精度的字串,或者將其格式化為指定精度的輸入數字。精度描述用於表達值的數字位數。

如果“precision”引數的值不在 [0, 100] 範圍內,則會丟擲“RangeError”異常。如果未為此方法指定“precision”引數值,則返回相同的輸出。

注意:如果精度值大於數字的總位數,則會在數字末尾新增額外的零。

語法

以下是 JavaScript Number 的toPrecision()方法的語法:

toPrecision(precision)

引數

此方法採用一個名為“precision”的可選引數,如下所述:

  • precision(可選) - 指定有效數字個數的整數。

返回值

此方法返回格式化為指定精度的數字。

示例 1

JavaScript number 的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

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>

輸出

上述程式根據指定的精度格式化輸入值。

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
廣告