Skip to content

JavaScript round to 1 decimal | Example code

  • by

Use math round() method with arithmetic logic to get round to 1 decimal of given number in JavaScript.

Math.round(num * 10) / 10

You can also use the toFixed() function.

var num = 2;
var roundedString = num.toFixed(2);// 2.00

Example round to 1 decimal in JavaScript

Simple example code.

<!doctype html>
  <head>

    <script>
      var number = 12.3456789
      var rounded = Math.round(number * 10) / 10

      console.log(rounded)

    </script>
  </head>
  <body>

  </body>
  </html>

Output:

JavaScript round to 1 decimal

if you want it to have one decimal place, even when that would be a 0, then add this

var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!

// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS round code.

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