Description
The JavaScript Number method toPrecision()
returns a string representing the given number to the specified precision.
- Precision defines the total number of digits in a number, on both sides of a decimal point.
- It returns a new string and doesn't change the original number.
- It is commonly used to convert a number to a string of fixed length, with its value rounded to the precision digits.
Syntax
The method toPrecision()
has the below syntax, where num
is a string.
num.toPrecision(precision)
Parameters
The method allows the below parameters.
precision
(optional)
- It is a number that represents the number of digits, including both sides of the decimal point.
- If the value is a non-integer number, the value is rounded to the nearest integer.
- If this argument is omitted, the entire number is returned.
Result
Returns a string that represents the given number rounded to the precision
digits.
Example 1: Using the Method
The below example shows the basic usage of the method.
var num = 123.45678;
// Without the argument
document.write(num.toPrecision()); // Prints: 123.45678 -> same as toString()
// With the argument
document.write(num.toPrecision(1)); // Prints: 1e+2 -> sometimes, exponential notation is used
document.write(num.toPrecision(2)); // Prints: 1.2e+2
document.write(num.toPrecision(5)); // Prints: 123.46 -> rounded to the nearest decimal value
document.write(num.toPrecision(10)); // Prints: 123.4567800 <- zeroes padded to get required precision
// Using exponential values
document.write((1.2345e+10).toPrecision(2)); // Prints: 1.2e+10
document.write((1.2345e-10).toPrecision(2)); // Prints: 1.2e-10
// Using negative values
document.write((-1.2345).toPrecision(2)); // Prints: -1.2
Output:
123.45678
1e+2
1.2e+2
123.46
123.4567800
1.2e+10
1.2e-10
-1.2
Example 2: Method Returns RangeError
If the argument precision
is not between 1 and 100, the method returns a RangeError
.
var num = 123.45678;
// Throws RangeError
document.write(num.toPrecision(0)); // Throws RangeError
document.write(num.toFixed(101)); // Throws RangeError
document.write(num.toFixed(Infinity)); // Throws RangeError
// Using NaN also throws RangeError
document.write(num.toPrecision(NaN)); // Throws RangeError
document.write(num.toPrecision("abc")); // Throws RangeError
Output:
RangeError: toPrecision() argument must be between 1 and 100
Overall
The JavaScript Number method toPrecision()
returns a string representing the given number to the specified precision.