JavaScript Math.round() 方法接受一个数值作为参数,将其四舍五入到最接近的整数并返回结果。
Math.round() 方法的工作原理如下 -
如果数字的小数部分小于 0.5,则 Math.round() 返回小于或等于 x 的最大整数。 如果数字的小数部分为 0.5 或更大,则 Math.round() 返回大于或等于 x 的最小整数。
语法
以下是 JavaScript Math.round() 方法的语法 -
Math.round(x);
参数
此方法只接受一个参数。下面描述相同 -
- x: 要四舍五入的数字。
返回值
此方法返回最接近给定数字的整数。如果小数部分为 .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("QikepuCom");
let value2 = Math.round();
document.write(value1, "<br>", value2);
</script>
</body>
</html>
输出
正如我们在输出中看到的那样,它返回了 “NaN”。