JavaScript 中的 Math.ceil() 和 Math.round() 方法有什么区别?
javascriptobject oriented programmingprogramming
Math.ceil() 和 Math.round() 方法的区别在于,前者向上舍入(向较大值舍入)将数字四舍五入为最接近的整数,而后者向下舍入(向较小值舍入)将数字四舍五入为最接近的整数。让我们分别检查一下这两种方法。
Math.ceil()
Math.ceil() 方法将作为参数传递的数字四舍五入为最接近的整数,以获得更大的值。
示例
在下面的例子中,当数字 5.34 作为参数传递时,Math.ceil() 将其四舍五入为 6,该值大于实际数字。
<html> <body> <script> document.write(Math.ceil(5.34)); </script> </body> </html>
输出
6
Math.round()
Math.round() 方法将作为参数传递的数字四舍五入为最接近的整数,以获得较低的值。
示例
在下面的例子中,当数字 5.34 作为参数传递时,Math.round() 将其四舍五入为 5,这比实际数字要低。
<html> <body> <script> document.write(Math.round(5.34)); </script> </body> </html>
输出
5