This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

toPrecision

Summary

Represents a number either in exponential or fixed-point notation with a specified number of digits.

Syntax

toPrecision([ precision ])
precision
Optional. The number of significant digits. Must be in the range 1 - 21, inclusive.

Return Value

For numbers in exponential notation, precision - 1 digits are returned after the decimal point. For numbers in fixed notation, precision significant digits are returned.

If precision is not supplied or is undefined , toString() is called instead.

Examples

Using toPrecision to format the decimal presentation of a number.

var pie = 3.14159;

// Call passed through to toString()
pie.toPrecision();
// Returns: "3.14159"

pie.toPrecision(5);
// Returns: "3.1416"

pie.toPrecision(2);
// Returns: "3.1"

pie.toPrecision(1);
// Returns: "3"

// Watch out for exponential notation
(1234.5).toPrecision(2);
// Returns "1.2e+3"

Remarks

Throws

RangeError when a fractionDigits outside the bounds of 1 - 21 (inclusive) was given.

See also

Other articles

External resources

Specification

15.7.4.7 Number.prototype.toPrecision(precision)

ECMAScript® Language Specification Standard ECMA-262 5.1 Edition / June 2011

Attributions

  • Microsoft Developer Network: Article