Skip to content

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

Chromeyes
Edgeyes
Firefox1
Internet Exploreryes
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes

1 Comment »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: