JavaScript Number.toPrecision()

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"

toPrecision() syntax Top ↑

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.

Precision means significant digits Top ↑

console.log((11.257).toPrecision(2)); // "11"
console.log((11.257).toPrecision(5)); // "11.257"
console.log((1.1257).toPrecision(3)); // "1.13"

toPrecision() returns a string Top ↑

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"

Trailing zeros can be significant Top ↑

console.log((11.257).toPrecision(6)); // "11.2570"

The trailing zero is part of the formatted string because six significant digits were requested.

When toPrecision() uses scientific notation Top ↑

console.log((11257).toPrecision(3)); // "1.13e+4"
console.log((11257).toPrecision(2)); // "1.1e+4"

Valid precision range Top ↑

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
}

toPrecision() vs toFixed() Top ↑

const value = 12.3456;
console.log(value.toFixed(2));      // "12.35" - 2 decimal places
console.log(value.toPrecision(2));  // "12" - 2 significant digits

See toFixed() when you need a fixed count of decimal places.

Convert text input before formatting Top ↑

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().

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer