JavaScript toFixed() | Round a number to specified number of decimals

The JavaScript toFixed() method is used when we need to round a number to particular number of decimals or decimal places. This method first converts the number to a string, then rounds the converted string to specified number of decimals. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

  <script>
    let num = 137.4356;
    document.getElementById("xyz").innerHTML = num.toFixed(2);
  </script>
   
</body>
</html>
Output

Please note: If the specified number of decimals are higher than the number of digits after the decimal point, then zeros will be added automatically. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

  <script>
    let num = 137.4356;
    document.getElementById("xyz").innerHTML = num.toFixed(6);
  </script>
   
</body>
</html>
Output

JavaScript toFixed() Syntax

The syntax of toFixed() method in JavaScript is:

number.toFixed(x)

The parameter x is an optional parameter, refers to an integer value, used to round a number to specified number of x decimal places. Its default value is 0.

Please note: The toFixed() method returns string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

  <script>
    let num = 137.4356;
    let res = num.toFixed(2);
    document.getElementById("xyz").innerHTML = typeof(res);
  </script>
   
</body>
</html>
Output

Other methods to do similar job

Here are the list of methods that are used to either round a number in other way, or to do similar type of job.

  • Math.ceil() - round a number up to its nearest largest integer.
  • Math.floor() - round a number up to its nearest smallest integer.
  • Math.round() - round a specified number to its nearest integer value.
  • toPrecision() - format a number to specific length.
  • Math.trunc() - find the integer part of a number.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋