toFixed, toExponential, and toPrecision
What you'll learn: How to format numbers as strings with specific decimal places, scientific notation, or a set number of significant digits.
Why Format Numbers?
Sometimes you need to display numbers in a specific way—like showing exactly two decimal places for currency, or using scientific notation for very large values. JavaScript numbers have three built-in methods that convert numbers to formatted strings.
The Three Formatting Methods
toFixed(digits)
Formats a number with a fixed number of decimal places. It rounds if necessary and always returns a string.
let price = 19.567;
price.toFixed(2); // "19.57" (rounded to 2 decimals)
let whole = 100;
whole.toFixed(2); // "100.00" (adds zeros)
toExponential(digits)
Formats a number in exponential notation (scientific notation). The optional digits parameter specifies how many digits appear after the decimal point.
let big = 123456;
big.toExponential(2); // "1.23e+5"
let small = 0.000123;
small.toExponential(2); // "1.23e-4"
toPrecision(digits)
Formats a number to a total number of significant digits, automatically choosing between fixed or exponential notation.
let num = 123.456;
num.toPrecision(4); // "123.5" (4 significant digits)
num.toPrecision(2); // "1.2e+2" (switches to exponential)
Key Difference
Think of it like formatting a photo: toFixed crops to a specific frame size, toExponential zooms out to see the whole picture with a scale indicator, and toPrecision automatically picks the best view based on what you want to highlight.
Key Takeaway: Use toFixed() for decimals, toExponential() for scientific notation, and toPrecision() for significant digits—all return formatted strings, not numbers.