Open In App

JavaScript Number toPrecision() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The JavaScript Number toPrecision( ) method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length. 

Syntax:

number.toPrecision(value)

Parameters: This method accepts a single optional parameter. 

  • value: This parameter represents the value of the number of significant digits in the formatted number. 

Return Value: The toPrecision() method in JavaScript returns a string in which the number is formatted to the specified precision.

Below is an example of the Number toPrecision( ) Method.

Example 1: 

Javascript




let num=213.45689;
console.log(num.toPrecision(3));


Output:

213

Example 2: Passing no arguments in the toPrecision() method, If no arguments are passed to the toPrecision() method then the formatted number will be exactly the same as the input number. Though, it will be represented as a string rather than a number.

Javascript




let num=213.45689;
console.log(num.toPrecision());


Output:

213.45689

Example 3: Passing an argument in the toPrecision() method, If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision. 

Javascript




let num=213.45689;
console.log(num.toPrecision(4));


Output:

213.5

Example 4: Passing an argument that results in the addition of null in the output, If the length of precision passed to the toPrecision() method is greater than the original number then zeros are appended to the input number to meet the specified precision.

Javascript




let num=213.45689;
console.log(num.toPrecision(12));
 
let num2 = 123;
console.log(num2.toPrecision(5));


Output:

213.456890000
123.00

Note: If the precision specified is not between 1 and 100 (inclusive), it results in a RangeError.

Supported Browsers:

  • Google Chrome 1 and above
  • Internet Explorer 5.5 and above
  • Firefox 1 and above
  • Apple Safari 2 and above
  • Opera 7 and above

We have a complete list of Javascript Number Objects methods, to check those please go through this Javascript Number Complete reference article.



Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads