Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript toPrecision() Method

JavaScript toPrecision() Method

Number Object Reference JavaScript Number object

Example

Formats a number to a specified length:

var

num

=

new

Number

(

13.3714

)

;

var

n

=

num

.

toPrecision

(

2

)

;

n Output result:

Try it »

Definition and Usage

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

The toPrecision() method returns the string representation of the number object at the specified precision, rounded to the number of digits specified by the precision parameter.


Browser support

Method
toPrecision() Yes Yes Yes Yes Yes

Syntax

number

.toPrecision(x)

Parameter value

Parameters Description
x

Optional. Specifies the number of significant digits, a value between 1 and 100 inclusive. If omitted, the toString() method is called, returning the original number as a string.

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

Return Value

Type Description
String Numeric format with specified precision

Technical Details

JavaScript version: 1.5

More examples

Example

Format a number to a specified length using different radices:

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, c and d Output result:

Try it »

Example

An error occurs when the parameter exceeds 100:

var

numObj

=

5.123456

;

//

Without parameters, outputs the string format of the number

console

.

log

(

numObj

.

toPrecision

(

)

)

;

//

Output 5.123456

//

Returns in exponential notation

console

.

log

(

(

1234.5

)

.

toPrecision

(

2

)

)

;

//

"1.2e+3"

//

Exceeding 100 causes an error

console

.

log

(

(

1234.5

)

.

toPrecision

(

200

)

)

;

Test result:


Number Object Reference JavaScript Number object