toFixed(digits) formats a Number using a fixed number of digits after the decimal point and returns the result as a string.
const value = 56.879654;
console.log(value.toFixed(4)); // "56.8797"
number.toFixed(digits)digits controls the number of decimal places. If omitted, it defaults to 0.
const value = 11.257;
console.log(value.toFixed(2)); // "11.26"
console.log((11.25).toFixed(1)); // "11.3"
console.log((11.978).toFixed(4)); // "11.9780"
console.log((5).toFixed(2)); // "5.00"
Modern JavaScript allows digits from 0 through 100. Values outside that range throw a RangeError.
try {
console.log((3.14).toFixed(101));
} catch (error) {
console.log(error.name); // RangeError
}
const formatted = (12.345).toFixed(2);
console.log(formatted); // "12.35"
console.log(typeof formatted); // "string"
Form values are strings. Convert the input first with parseFloat() or Number(), validate it, then format it.
const amount = Number("19.9");
if (Number.isFinite(amount)) {
console.log(amount.toFixed(2)); // "19.90"
}
toFixed() formats the binary floating-point Number that JavaScript actually stores. Some decimal fractions cannot be represented exactly, so edge cases may not round as expected from the written decimal alone.
console.log((2.55).toFixed(1)); // may be "2.5" because of stored binary value
For directional rounding rules, also see Math.ceil() and Math.floor().
toFixed(2) can produce two decimal places, but it does not add locale-aware separators or currency symbols. For currency shown to users, Intl.NumberFormat is usually the better presentation API.
const formatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
});
console.log(formatter.format(19.9));
toFixed() controls digits after the decimal point. toPrecision() controls the total number of significant digits.
See parseInt(), parseFloat(), PHP number_format(), and toPrecision().
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.