Number.prototype.toFixed()

Converts a number into a string with a given number of decimal places.

Returns
A string with the number written in fixed-point notation.
On this page

Example

#
JavaScript
const average = 81.66666666666667

console.log(average.toFixed(1))
console.log((5).toFixed(2))
console.log(typeof average.toFixed(1))
console.log((0.1 + 0.2).toFixed(2))
Console
81.7
5.00
string
0.30

Definition and usage

#

The toFixed(digits) method rounds a number to the given number of decimal places and returns the result as a string. Missing places are padded with zeros, so (5).toFixed(2) gives "5.00".

The result is text, not a number. It’s fine for display, but for further calculations you need to convert it back with Number().

Rounding inherits the imprecision of floating-point numbers: (1.005).toFixed(2) gives "1.00", because 1.005 is stored in memory as slightly less than 1.005. For currency amounts, use Intl.NumberFormat.

Syntax

#
Syntax
number.toFixed()
number.toFixed(digits)

Parameters

#
  • digits

    0-100, optional

    The number of decimal places. Defaults to 0.

More examples

#
The rounding pitfall
JavaScript
console.log((1.005).toFixed(2))
console.log(Math.round(1.005 * 100) / 100)
Console
1.00
1

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To format amounts with a currency symbol and a thousands separator, use Intl.NumberFormat, not toFixed().
  • Remember that the result is a string. Number(x.toFixed(2)) gives back a number.

Related entries

#

Spotted a mistake or missing an example? Write to us.