What is toPrecision() in Javascript?
toPrecision() is a Number method that is used to format a number to a specific precision. In other words, the toPrecision() method formats a number to a given length by either rounding off to reduce the length or adding zeros to increase the length.
Declaration
The toPrecision() method is declared as follows:
num.toPrecision(len)
num: The number to be formatted to the precisionlen.len: The precision in whichnumwill be formatted;lenis an optional parameter.
Note:
- If
lenis not passed as a parameter, thetoPrecision()method simply convertsnumto a string.lenmust be in the range 1 to 100. Otherwise, RangeError is thrown.
Return value
The toPrecision() method returns a string that represents the number num in precision len.
Browser compatibility
The toPrecision() method is supported by the following browsers:
- Edge 12
- Firefox 1
- Google Chrome 1
- Internet Explorer 5.5
- Opera 7
- Safari 2
Example
Consider the code snippet below, which demonstrates the use of the toPrecision() method:
var num = 15.199console.log("15.199 to precision of no length is: ",num.toPrecision());console.log("15.199 to precision of length 3 is: ",num.toPrecision(3));console.log("15.199 to precision of length 7 is: ",num.toPrecision(7));
Explanation
A number num is initialized with num = 15.199 in line 1.
- line 3: The
toPrecision()method is not passed the input parameter, sonumis simply converted to a string. - line 5:
numis converted to the precision of length = 3 by rounding offnumto make it of length = 3. - line 7:
numis converted to the precision of length = 7 by adding zeros to the right ofnumto make it of length = 7.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved