What is the toPrecision() method in JavaScript?

The toPrecision() method rounds a number to a specified precision or significant digits. If the rounded number requires more digits than the original number, the method adds decimals and nulls to create the specified format.

If the toPrecision() method is called on an object other than a number, a TypeError occurs.

Syntax

The toPrecision() method is declared as follows:

Parameters

The toPrecision() method takes an optional single parameter x, which is an integer number representing the number of significant digits.

  • If the value of x is not within the range 0 - 100, a RangeError occurs.

  • If x is not an integer, it is rounded to the nearest integer.

Return value

The toPrecision() method returns a string rounded to x significant digits. If x is not specified, the number is returned in string form without any rounding.

Examples

The following code shows the use of the toPrecision() method in JavaScript:

//Example 1
var num = 1.234567;
console.log(num.toPrecision());
//Example 2
console.log(num.toPrecision(4));
//Example 3
console.log(num.toPrecision(2));
//Example 4
console.log(num.toPrecision(1));

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved