toPrecision(precision) formats a Number to a specified number of significant digits. It returns a string and may use fixed-point or exponential notation.
const value = 1445.32678;
console.log(value.toPrecision(6)); // "1445.33"
number.toPrecision(precision)If precision is omitted, the method behaves similarly to converting the Number to a string without forcing a specific count of significant digits.
console.log((11.257).toPrecision(2)); // "11"
console.log((11.257).toPrecision(5)); // "11.257"
console.log((1.1257).toPrecision(3)); // "1.13"
The older version of this tutorial treated the returned value as a number. That is incorrect: the formatted result is a string.
const result = (1445.32678).toPrecision(6);
console.log(result); // "1445.33"
console.log(typeof result); // "string"
console.log((11.257).toPrecision(6)); // "11.2570"The trailing zero is part of the formatted string because six significant digits were requested.
console.log((11257).toPrecision(3)); // "1.13e+4"
console.log((11257).toPrecision(2)); // "1.1e+4"
When supplied, precision must be between 1 and 100. Values outside the supported range throw a RangeError.
try {
(12.34).toPrecision(0);
} catch (error) {
console.log(error.name); // RangeError
}
const value = 12.3456;
console.log(value.toFixed(2)); // "12.35" - 2 decimal places
console.log(value.toPrecision(2)); // "12" - 2 significant digitsSee toFixed() when you need a fixed count of decimal places.
Methods such as toPrecision() belong to Number values. Convert and validate text before using them.
const value = parseFloat("1445.32678");
if (!Number.isNaN(value)) {
console.log(value.toPrecision(6));
}Related conversion pages: parseInt(), parseFloat(), and NaN checks.
Also review Math.ceil(), Math.floor(), and toFixed().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.