Skip to content

JavaScript round method | Up-Down, Up to decimal example code

  • by

The javaScript round method is used to rounds a number to the nearest integer. It can do round up or round down a number. You have to just pass the number as a parameter into the method.

Syntax

Math.round(x)

Examples of the JavaScript round method

Let’s do round a number to the nearest integer in js:-

 <!DOCTYPE html> 
    <html> 
    <body> 
            <script language="JavaScript">
                var num = 98.33668;
                var n = Math.round(num);
                alert(n);
            </script>     
    </body> 
    </html> 

Output:

JavaScript round method

Round up

Simply automatic will round up integer (number). If the first decimal above and equal the 5.

Math.ceil(1.4)

ceil() Method also Round a number upward to its nearest integer:

var num = 98.33;
var n = Math.ceil(num)

Round down

Same as round up not need specials instructions. If first decimal is below 5.

<script language="JavaScript">
        var num = 98.15;
        var n = Math.round(num)
        alert(n);
</script>    

floor() Method also can use to Round a number downward to its nearest integer:

Round to 2 decimals

Math.round(num * 100) / 100

Round to 1 decimal

Math.round(num * 10) / 10

Round to nearest 10

var number = 33; </code>
<code>console.log(Math.round(number / 10) * 10);

Round to 4 decimal places

myNumber.toFixed(4);

Q: How to JavaScript round float?

Answer: Use toFixed() function.

(6.688689).toFixed(); // equal to 7
(6.688689).toFixed(1); // equal to 6.7
(6.688689).toFixed(2); // equal to 6.69

Read more: JavaScript toFixed() method

Do comment if you have any doubts and suggestion on topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading