# Number.toPrecision ()

## Why toPrecision ?

The JavaScript toPrecision () method formats a number to create the specified length.

Syntax:

numObj.toPrecision([precision])

• precision (optional): The number of digits. If omitted, it returns the entire number (without any formatting)

return

• 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 `Number.prototype.toFixed()` method, which also applies to `toPrecision()`.
• If the `precision` argument is omitted, behaves as `Number.prototype.toString()`. If the `precision` argument is a non-integer value, it is rounded to the nearest integer.

### JavaScript toPrecision Examples

Example 1

``````        var num = new Number(7.123456);
console.log("num.toPrecision() is " + num.toPrecision());

console.log("num.toPrecision(4) is " + num.toPrecision(4));

console.log("num.toPrecision(2) is " + num.toPrecision(2));

console.log("num.toPrecision(1) is " + num.toPrecision(1));``````

output:

num.toPrecision() is 7.123456
num.toPrecision(4) is 7.123
num.toPrecision(2) is 7.1
num.toPrecision(1) is 7

Example 2

``````        let num = 24.5497;
let x1 = num.toPrecision();
let x2 = num.toPrecision(2);
let x3 = num.toPrecision(3);
let x4 = num.toPrecision(10);

console.log(x1)
console.log(x2)
console.log(x3)
console.log(x4)``````

output:

24.5497
25
24.5
24.54970000

Example 3

``````        let num = 0.4596;
let x1 = num.toPrecision();
let x2 = num.toPrecision(2);
let x3 = num.toPrecision(3);

console.log(x1)
console.log(x2)
console.log(x3)``````

output:

0.4596
0.46
0.460

### Browser Support

 Chrome yes Edge yes Firefox 1 Internet Explorer yes Opera yes Safari yes Android webview yes Chrome for Android yes Edge mobile yes Firefox for Android 4 Opera Android yes

### 1 Comment »

This site uses Akismet to reduce spam. Learn how your comment data is processed.