JavaScript Math round to 2 decimal places | Example code

  • by

Simple arithmetic login with Math round method you can round given number to 2 decimal places in Python.

Math.round(num * 100) / 100

Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :

Math.round((num + Number.EPSILON) * 100) / 100

Example Math round to 2 decimal places in JS

Simple example code.

<!DOCTYPE html>

<body>
  <script>
   let n = 10200300.5555;
   let res = Math.round(n * 100) / 100

   console.log(res);
 </script>
</body>
</html>

Output:

JavaScript Math round to 2 decimal places

If the value is a text type use this code

parseFloat("123.456").toFixed(2);

Using toFixed method, It seems like Math.round is a better solution. But it is not!

Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!

In some cases it will NOT round correctly:

var numb = 123.23454;
numb = numb.toFixed(2);

Do comment if any doubts or suggestions on this JS math format topic.

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

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.