Tutorialspoint.dev

JavaScript | Math.round( ) function

The Math.round() function in JavaScript is used to round a number to its nearest integer. If the fractional part of the number is greater than or equal to .5, the argument is rounded to the next higher integer. If the fractional part of the number is less than .5, the argument is rounded to the next lower integer.

Syntax:

Math.round(var);

Parameters: This function accepts a single parameter, var. It is the number which you want to round off.



Return Value: The Math.round() function returns the value of the given number rounded to the nearest integer.

Below are some examples to illustrate the Math.round() function:

  1. Rounding Off a number to its nearest integer: To round off a number to its nearest integer, the math.round() function should be implemented in the following way:

    <script type="text/javascript">
        var round =Math.round(5.8);
        document.write("Number after rounding : " + round); 
    </script>

    /div>

    Output:

    Number after rounding : 6
  2. Rounding Off a negative number to its nearest integer: The Math.round() function itself rounds off a negative number when passed as parameter to it. To round off a negative number to its nearest integer, the Math.round() function should be implemented in the following way:

    <script type="text/javascript">
        var round =Math.round(-5.8);
        document.write("Number after rounding : " + round); 
    </script>

    Output:

    Number after rounding : -6
  3. Math.round() function, when parameter has “.5” as decimal: Below program shows the result of Math.round() function when the parameter has “.5” in decimal.

    <script type="text/javascript">
        var round =Math.round(-12.5);
        document.write("Number after rounding : " + round);
        var round =Math.round(12.51);
        document.write("Number after rounding : " + round); 
    </script>

    Output:

    Number after rounding : -12
    Number after rounding : 13


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter