JavaScript Math.round() 方法
JavaScript Math.round() 方法接受一个数值作为参数,将其四舍五入为最接近的整数并返回结果。
Math.round() 方法的工作原理如下:-
- 如果数字的小数部分小于 0.5,Math.round() 将返回小于或等于 x 的最大整数。
- 如果数字的小数部分大于或等于 0.5,Math.round() 将返回大于或等于 x 的最小整数。
语法
以下是 JavaScript Math.round() 方法的语法:-
Math.round(x);
参数
此方法仅接受一个参数。下文同样描述 -
x: 需要四舍五入的数字。
返回值
此方法返回最接近给定数字的整数。如果小数部分为 0.5 或更大,则向上舍入。否则向下舍入。
示例 1
在下面的示例中,我们演示了 JavaScript Math.round() 方法的基本用法 -
<html> <body> <script> let value1 = Math.round(5.49); document.write(value1, "<br>"); let value2 = Math.round(5.50); document.write(value2, "<br>"); let value3 = Math.round(5.99); document.write(value3); </script> </body> </html>
输出
如果我们执行上述程序,指定的正整数将被四舍五入为最接近的整数。
示例 2
在这里,我们将负数参数传递给 Math.round() 方法 -
<html> <body> <script> let value1 = Math.round(-5.49); document.write(value1, "<br>"); let value2 = Math.round(-5.50); document.write(value2, "<br>"); let value3 = Math.round(-5.99); document.write(value3); </script> </body> </html>
输出
如果执行该程序,它将返回"-5"、"-5"和"-6"作为结果。
示例 3
如果我们将"null"作为参数传递给此方法,它将返回"0"作为结果 -
<html> <body> <script> let value = Math.round(null); document.write(value); </script> </body> </html>
输出
正如我们在输出中看到的,它返回了"null"。
示例 4
如果我们向此方法提供一个非数字或空数字作为参数,它将返回"NaN"作为结果 -
<html>
<body>
<script>
let value1 = Math.round("Tutorialspoint");
let value2 = Math.round();
document.write(value1, "<br>", value2);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它返回了"NaN"。

