JavaScript Number toPrecision()
Example
Format a number to a specified length:
let num = 13.3714;
let n = num.toPrecision(2);
Try it Yourself »
Format a small number:
let num = 0.001658853;
num.toPrecision(2);
num.toPrecision(3);
num.toPrecision(10);
Try it Yourself »
More examples below.
Description
The toPrecision()
method formats a number to a specified length.
A decimal point and nulls are added (if needed), to create the specified length.
Syntax
number.toPrecision(x)
Parameters
Parameter | Description |
x | Optional. The number of digits. If omitted, the number is returned without any formatting. |
Return Value
Type | Description |
A string | The number formatted to the specified precision. |
More Examples
Format a number to a specified length:
let num = 13.3714;
num.toPrecision(2);
num.toPrecision(3);
num.toPrecision(10);
Try it Yourself »
No formatting:
let num = 13.3714;
num.toPrecision();
Try it Yourself »
Browser Support
toPrecision()
is an ECMAScript3 (ES3) feature.
ES3 (JavaScript 1999) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.