JavaScript 数学(Math)对象方法

JavaScript Math.round() 方法是四舍五入方法。如果给定的数字已经是整数,则round()方法直接返回。

语法

round() 方法由以下语法表示:

Math.round(num)

    参数

    num - 一个数字。

    返回

    给定数字的最接近的整数值。

    方法示例

    这里,我们将通过各种例子来了解round()方法。

    示例1

    让我们看一个例子,将给定的数字增加到最接近的整数值。

    <script>
    document.writeln(Math.round(7.2)+"<br>");
    document.writeln(Math.round(0.6));
    </script>
    • 1
    • 2
    • 3

    输出:

    7
    1

    示例2

    在本例中,我们将使用负数的 round() 方法。

    <script>
    document.writeln(Math.round(-7.2)+ "<br>");
    document.writeln(Math.round(-0.6));
    </script>
    • 1
    • 2
    • 3

    输出:

    -7
    -1