JavaScript toPrecision() | Format a number to specific length

The JavaScript toPrecision() method is used when we need to format a number to specific length. For example:

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

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

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

That is, the number 137.4356 is formatted to 5 digits, from start.

JavaScript toPrecision() Syntax

The syntax of toPrecision() method in JavaScript is:

number.toPrecision(x)

The parameter x is optional, refers to an integer value, used to format the number to x size or length or number of digits. Without x, the toPrecision() method return the as-it-is number.

JavaScript toPrecision() Example

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

   <p id="para1"></p>
   <p id="para2"></p>
   <p id="para3"></p>
   <p id="para4"></p>
   <p id="para5"></p>
   <p id="para6"></p>
   <p id="para7"></p>

  <script>
    let num = 12.3403;
    
    document.getElementById("para1").innerHTML = num.toPrecision(2);
    document.getElementById("para2").innerHTML = num.toPrecision(3);
    document.getElementById("para3").innerHTML = num.toPrecision(4);
    document.getElementById("para4").innerHTML = num.toPrecision(5);
    document.getElementById("para5").innerHTML = num.toPrecision(6);
    document.getElementById("para6").innerHTML = num.toPrecision(7);
    document.getElementById("para7").innerHTML = num.toPrecision(8);
  </script>
   
</body>
</html>
Output

Please note: Zeroes are added to create specified length.

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.
  • toFixed() - round a number to particular number of decimals.
  • Math.trunc() - find the integer part of a number.

JavaScript Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋