toPrecision Method (Number) (JavaScript)

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

Syntax


numObj.toPrecision([precision])  

Parameters

numObj
Required. A Number object.

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, the toString method is called instead.

Example

The following code shows how to use toPrecision.

var num = new Number(123);  
var prec = num.toPrecision();  
document.write(prec);  
document.write("<br/>");  

num = new Number(123.456);  
prec = num.toPrecision(5);  
document.write(prec);  

// Output:  
// 123  
// 123.46  

Requirements

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported Store apps (Windows 8 and Windows Phone 8.1). See Version Information.

Applies To: Number Object

See Also

toFixed Method (Number)
toExponential Method (Number)