Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Number.prototype.toPrecision: significant digits

toPrecision returns text with the requested number of significant digits, choosing fixed or exponential notation.

Version: ECMAScript 3 onward; example target: Node.js 24.22.2

Syntax

number.toPrecision(precision)

number.toPrecision(precision) formats the value with precision significant digits. If the argument is omitted or is undefined, the method immediately returns the number’s ordinary ToString result. A provided argument undergoes ToIntegerOrInfinity: a fractional part truncates toward zero and NaN becomes 0; for a finite receiver, a result outside 1..100 throws RangeError.

After converting a provided argument, a NaN or ±Infinity receiver returns its ordinary text before the range check, so Infinity.toPrecision(0) yields "Infinity". An object supplied as precision can nevertheless throw during conversion. For a finite value, the method uses exponential notation when the decimal exponent is less than -6 or at least precision; otherwise it uses fixed notation. It rounds to the nearest result, choosing the larger magnitude on a tie after separating the sign.

The method has existed since ECMAScript 3, is not generic, and throws TypeError for a receiver other than a Number or boxed Number. It returns text, not a number. Number uses binary representation, so rounding can surprise; use Intl.NumberFormat for locale-aware presentation.

Examples

console.log((1234.5).toPrecision(4), (1234.5).toPrecision(3));
console.log((0.0000012345).toPrecision(3), (0.00000012345).toPrecision(3));
console.log((7).toPrecision(), (-0).toPrecision(3));
console.log(Infinity.toPrecision(0));
try { console.log((1).toPrecision(0)); } catch (error) { console.log(error.name); }
try { Number.prototype.toPrecision.call("1", 2); } catch (error) { console.log(error.name); }

Result

1235 1.23e+3
0.00000123 1.23e-7
7 0.00
Infinity
RangeError
TypeError

The example compares fixed and exponential notation and shows negative zero, Infinity, and range/receiver errors.

Sources