JavaScript Number Formatting: toFixed and toPrecision
Quick answer
Number formatting produces strings intended for display. toFixed chooses fractional digits; toPrecision chooses significant digits. Neither changes the original Number.
How it works
number.toFixed(digits) uses a digit count from 0 to 100; values with magnitude at least 10^21 use ordinary number-to-string formatting. number.toPrecision(precision) accepts 1 to 100 significant digits or uses ordinary conversion when omitted. It may use exponent notation. toExponential formats scientific notation. Binary rounding still affects displayed results.
const n = 12.5;console.log(n.toFixed(2), n.toPrecision(2), typeof n.toFixed(2));Expected output in Node.js:
12.50 13 stringFixed uses fractional digits; precision uses significant digits.
console.log((1234).toExponential(2), (0.125).toFixed(3));Expected output in Node.js:
1.23e+3 0.125Scientific notation normalizes the coefficient.
Common mistakes
The return value is text, so adding it to a Number can concatenate rather than add numerically. Formatting is not exact decimal arithmetic.
Practice
Format one measurement as fixed decimals and significant digits, then compare the strings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Number Formatting: toFixed and toPrecision — Knowledge Check
Apply the taught concept and predict the output.
Which method requests exactly two fractional digits for an ordinary small finite Number?
What is the type of (8).toPrecision(2)?
Which exception is expected for (5).toFixed(101)?
What is the exact console output in JavaScript Number Formatting: toFixed and toPrecision example 1?
const n = 12.5;console.log(n.toFixed(2), n.toPrecision(2), typeof n.toFixed(2));What is the exact console output in JavaScript Number Formatting: toFixed and toPrecision example 2?
console.log((1234).toExponential(2), (0.125).toFixed(3));