The
Number.toPrecision()
method returns a value with the specified number of significant digits.
Description
The
toPrecision()
method from JavaScript’s
Number
object lets you change numbers into strings with a specific number of significant digits. Significant digits are the meaningful numbers in a value that help show its accuracy, like how many numbers after or before the decimal point are important for understanding it well.
If you need a number use
parseFloat
to convert the result back into a number, see example.
Parameters
Number
— The number of significant digits you want in your output string.
Return Type
A
String
Examples
// Sample JavaScript
const myNumber = 1.5;
// All of these return a string NOT a number
myNumber.toPrecision(3); // 1.50
myNumber.toPrecision(4); // 1.500
myNumber.toPrecision(1); // 2
How do I convert it back to a Number?
It’s simple! Just use the
parseFloat()
method.
// Sample JavaScript
const myNumber = 1.5;
// These all return a number
parseFloat( myNumber.toPrecision(3) ); // 1.50
parseFloat( myNumber.toPrecision(4) ); // 1.500
parseFloat( myNumber.toPrecision(1) ); // 2
See Also
- Math.round()— Returns a value rounded to the nearest whole number.
- Number.toFixed()— Returns a value with the specified number of decimal places.
Full Developer Reference
Attribution
- "Original Content" by Mozilla Contributors, licensed under CC-BY-SA 2.5 | Modified from the Original