Number.prototype.toPrecision()

Summary

The toPrecision() method returns a string representing the Number object to the specified precision.

Syntax

numObj.toPrecision(precision)

Parameter

precision
An integer specifying the number of significant digits.

Returns

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 it is a non-integer value, it is rounded to the nearest integer.

Throws

RangeError
If precison is not between 1 and 100 (inclusive), a RangeError is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits.

Example

var numObj = 5.123456;
console.log("numObj.toPrecision()  is " + numObj.toPrecision());  //displays 5.123456
console.log("numObj.toPrecision(5) is " + numObj.toPrecision(5)); //displays 5.1235
console.log("numObj.toPrecision(2) is " + numObj.toPrecision(2)); //displays 5.1
console.log("numObj.toPrecision(1) is " + numObj.toPrecision(1)); //displays 5

// note that exponential notation might be returned in some circumstances
console.log((1234.5).toPrecision(2)); // "1.2e+3"

Specifications

Specification Status Comment
ECMAScript 3rd Edition. Implemented in JavaScript 1.5 Standard Initial definition.
ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

See Also

Document Tags and Contributors

Last updated by: fscholz,