Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Number:toPrecision

From MDC


Contents

[edit] Summary

Returns a string representing the Number object to the specified precision.

[edit] Syntax

number.toPrecision( [ precision ] )

[edit] Parameter

precision
An integer specifying the number of significant digits.

[edit] 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 toFixed method, which also applies to toPrecision.

If the precision argument is omitted, behaves as Number.toString. If it is a non-integer value, it is rounded to the nearest integer. After rounding, if that value is not between 1 and 100 (inclusive), a RangeError is thrown.

ECMA-262 only requires a precision of up to 21 significant digits. Other implementations may not support precisions higher than required by the standard.

[edit] Example

var num = 5.123456;
println("num.toPrecision() is " + num.toPrecision());   //displays 5.123456
println("num.toPrecision(4) is " + num.toPrecision(4)); //displays 5.123
println("num.toPrecision(2) is " + num.toPrecision(2)); //displays 5.1
println("num.toPrecision(1) is " + num.toPrecision(1)); //displays 5

[edit] See Also