The toPrecision() method returns a string representing the Number object to the specified precision.
Syntax
numObj.toPrecision([precision])
Parameters
precisionOptional- An integer specifying the number of significant digits.
Return value
A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the Number.prototype.toFixed() method, which also applies to toPrecision().
If the precision argument is omitted, behaves as Number.prototype.toString(). If the precision argument is a non-integer value, it is rounded to the nearest integer.
Exceptions
RangeError- If
precisionis not between1and100(inclusive), aRangeErroris thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits.
Examples
Using toPrecision
let numObj = 5.123456 console.log(numObj.toPrecision()) // logs '5.123456' console.log(numObj.toPrecision(5)) // logs '5.1235' console.log(numObj.toPrecision(2)) // logs '5.1' console.log(numObj.toPrecision(1)) // logs '5' numObj = 0.000123 console.log(numObj.toPrecision()) // logs '0.000123' console.log(numObj.toPrecision(5)) // logs '0.00012300' console.log(numObj.toPrecision(2)) // logs '0.00012' console.log(numObj.toPrecision(1)) // logs '0.0001' // note that exponential notation might be returned in some circumstances console.log((1234.5).toPrecision(2)) // logs '1.2e+3'
Specifications
| Specification |
|---|
| ECMAScript (ECMA-262) The definition of 'Number.prototype.toPrecision' in that specification. |
Browser compatibility
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toPrecision | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 5.5 | Opera Full support 7 | Safari Full support 2 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support 0.1.100 |
Legend
- Full support
- Full support
