JavaScript Number.toFixed()

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"

toFixed() syntax and return value Top ↑

number.toFixed(digits)

digits controls the number of decimal places. If omitted, it defaults to 0.

Rounding to a chosen number of decimal places Top ↑

const value = 11.257;
console.log(value.toFixed(2)); // "11.26"
console.log((11.25).toFixed(1)); // "11.3"

toFixed() adds trailing zeros when needed Top ↑

console.log((11.978).toFixed(4)); // "11.9780"
console.log((5).toFixed(2));      // "5.00"

Valid digits range Top ↑

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
}

toFixed() returns a string, not a Number Top ↑

const formatted = (12.345).toFixed(2);
console.log(formatted);        // "12.35"
console.log(typeof formatted); // "string"

Using toFixed() with form or text input Top ↑

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"
}

Floating-point rounding can look surprising Top ↑

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

Use Intl.NumberFormat for user-facing currency Top ↑

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() vs toPrecision() Top ↑

toFixed() controls digits after the decimal point. toPrecision() controls the total number of significant digits.

See parseInt(), parseFloat(), PHP number_format(), and toPrecision().

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