Open In App

JavaScript Number toPrecision() Method

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. 

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: 




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.




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. 




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.




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:

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


Article Tags :