JavaScript Number toFixed() 方法返回带或不带小数位的数值的表示形式。它包括一个名为 'digits' 的可选参数。但是,如果 digits 参数不在 '[0,100]' 范围内,则会引发 'RangeError' 的异常。此外,如果我们尝试在非数字的对象上调用此方法,则会引发 'TypeError' 异常。
注意:如果小数位数大于原始数字中的小数位数,则会在数字末尾添加额外的零。
语法
以下是 JavaScript Number toFixed() 方法的语法 -
toFixed(digits)
参数
此方法接受一个名为“digits”的可选参数,如下所述 -
- digits (optional) - 小数点后显示的位数。
返回值
此方法返回具有(或不具有)十进制值的数值的表示形式。
示例 1
以下示例演示了 JavaScript Number toFixed() 方法的用法。
<html>
<head>
<title>JavaScript toFixed() Method</title>
</head>
<body>
<script>
const val = 123.44;
document.write("Given value = ", val);
document.write("<br>Result = ", val.toFixed());
</script>
</body>
</html>
输出
上述程序生成如下所示的输出 -
Given value = 123.44
Result = 123
Result = 123
示例 2
如果我们将可选参数 'digits' 设置为 3,则此方法将表示小数点后有 3 位数字的数值。
<html>
<head>
<title>JavaScript toFixed() Method</title>
</head>
<body>
<script>
const val = 4553.4321343;
const digits = 3;
document.write("Given value = ", val);
document.write("<br>Digits = ", digits);
document.write("<br>Result = ", val.toFixed(digits));
</script>
</body>
</html>
输出
执行上述程序后,它返回一个小数点后具有指定位数的数字 -
Given value = 4553.4321343
Digits = 3
Result = 4553.432
Digits = 3
Result = 4553.432
示例 3
如果可选参数 'digits' 的值超出 [0, 100] 的范围,则 Number toFixed() 方法会引发 “RangeError” 异常。
<html>
<head>
<title>JavaScript toFixed() Method</title>
</head>
<body>
<script>
const val = 123.321123;
const digits = -1;
document.write("Given value = ", val);
document.write("<br>Digits = ", digits);
try {
document.write("<br>Result = ", val.toFixed(digits));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
一旦执行了上述程序,它就会抛出一个 'RangeError' 异常 -
Given value = 123.321123
Digits = -1
RangeError: toFixed() digits argument must be between 0 and 100
Digits = -1
RangeError: toFixed() digits argument must be between 0 and 100
示例 4
如果我们在一个不是数字的对象上调用 Number toFixed() 方法,它会抛出一个 “TypeError” 异常。
<html>
<head>
<title>JavaScript toFixed() Method</title>
</head>
<body>
<script>
const val = "abc";
const digits = 5;
document.write("Given value = ", val);
document.write("<br>Digits = ", digits);
try {
document.write("<br>Result = ", val.toFixed(digits));
} catch (error) {
document.write("<br>", error);
}
</script>
</body>
</html>
输出
上述程序将 'TypeError' 异常抛出为 −
Given value = abc
Digits = 5
TypeError: val.toFixed is not a function
Digits = 5
TypeError: val.toFixed is not a function