JavaScript toPrecision()Method

Number 对象参考手册JavaScript Number Object

Example

Format a number to a specified length:

var num = new Number(13.3714); var n=num.toPrecision(2);

nOutput:


Try it Yourself »

Definition and Usage

The toPrecision() method returns a numeric string of the specified length.

The toPrecision() method returns the string representation of the numeric object with the specified precision, rounding to the number of displayed digits specified by the precision parameter.


Browser Support

Method
toPrecision() Yes Yes Yes Yes Yes

Syntax

number.toPrecision(x)

Parameter Values

Parameter Description
x

Optional. Specifies the number of digits to convert to. This parameter is a value between 1 and 100 (inclusive). If this parameter is omitted, the toString() method is called, returning the string form of the original number.

If the precision parameter is not between 1 and 100 (inclusive), a RangeError will be thrown.

Return Value

Type Description
String A number formatted to the specified precision

Technical Details

JavaScript Version: 1.5


More Examples

Example

Format a number to a specified length using different bases:

var num = new Number(13.3714); var a = num.toPrecision(); var b = num.toPrecision(2); var c = num.toPrecision(3); var d = num.toPrecision(10);

a、b、canddOutput:


Try it Yourself »

Example

An error is reported if the parameter exceeds 100:

var numObj = 5.123456; //Without parameters, output the string format of a number console.log(numObj.toPrecision()); //Output 5.123456 //Return in exponential notation console.log((1234.5).toPrecision(2)); // "1.2e+3" //An error will be reported if it exceeds 100 console.log((1234.5).toPrecision(200));

Test result:



Number 对象参考手册JavaScript Number Object

Other extensions