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.
The toPrecision()
method is declared as follows:
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.
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.
The following code shows the use of the toPrecision()
method in JavaScript:
//Example 1var num = 1.234567;console.log(num.toPrecision());//Example 2console.log(num.toPrecision(4));//Example 3console.log(num.toPrecision(2));//Example 4console.log(num.toPrecision(1));
Free Resources