Easy Tutorial
❮ Prop Reset Value Jsref Foreach ❯

JavaScript toPrecision() Method

JavaScript Number Object

Example

Format a number to a specified length:

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

n Output:

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

Definition and Usage

The toPrecision() method returns a string representing the number to a specified precision.

The toPrecision() method returns a string representing the number object in a specified precision, rounded to the number of significant digits specified by the precision parameter.


Browser Support

Method Chrome Edge Firefox Safari Opera
toPrecision() Yes Yes Yes Yes Yes

Syntax

Parameter Values

Parameter Description
x Optional. Specifies the number of significant digits. This parameter is a value between 1 and 100 (inclusive). If omitted, the method calls toString(), 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 A number formatted to the specified precision

Technical Details

| JavaScript Version: | 1.5 | | --- | --- |


More Examples

Example

Format a number to different precisions:

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:

var num = new Number(13.3714);
document.write(num.toPrecision() + "<br>");
document.write(num.toPrecision(2) + "<br>");
document.write(num.toPrecision(3) + "<br>");
document.write(num.toPrecision(10));

Example

An error occurs if the parameter exceeds 100:

var numObj = 5.123456;

// Without a parameter, outputs the number as a string
console.log(numObj.toPrecision());  // Outputs 5.123456

// Returns in exponential notation
console.log((1234.5).toPrecision(2)); // "1.2e+3"

// Exceeding 100 throws an error
console.log((1234.5).toPrecision(200));

Test Results:


JavaScript Number Object

❮ Prop Reset Value Jsref Foreach ❯