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.
The toPrecision()
method formats a number to a specified length.
A decimal point and nulls are added (if needed), to create the specified length.
number.toPrecision(x)
Parameter | Description |
x | Optional. The number of digits. If omitted, the number is returned without any formatting. |
Type | Description |
A string | The number formatted to the specified precision. |
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 »
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 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!