The Number toFixed() method

By

Learn how the JavaScript Number toFixed() method returns a string with a number in fixed point notation, and how to set how many decimal digits to keep.

~~~

You can use toFixed() to get a string representing the number in fixed point notation:

(21.2).toFixed() //'21'

With no argument, it rounds to zero decimal places.

You can add an optional number setting the digits as a parameter:

(21.2).toFixed(0) //'21'
(21.2).toFixed(1) //'21.2'
(21.2).toFixed(2) //'21.20'
(21.2).toFixed(5) //'21.20000'

If the number has fewer decimals than you asked for, toFixed() pads with zeros. That’s what makes it handy for displaying prices: 21.2 becomes '21.20'.

Note the parentheses around the number. 21.toFixed(2) is a syntax error, because JavaScript reads the dot as a decimal point. Wrapping the literal in parentheses fixes it. With a variable you don’t need them.

It returns a string, not a number

This is the first thing to keep in mind. The result of toFixed() is a string:

typeof (21.2).toFixed(2) //'string'

So it’s a formatting tool, for the end of your pipeline, right before showing a value to the user. If you do math on the result, you’ll get string behavior:

(21.2).toFixed(2) + 1 //'21.201'

The + here concatenates. Do all your calculations first, and call toFixed() last.

The rounding surprise

toFixed() rounds, but it rounds the number as it’s actually stored, and floating point storage is not exact. This leads to results that look wrong:

(1.005).toFixed(2) //'1.00'
(4.35).toFixed(1) //'4.3'

You’d expect '1.01' and '4.4'. But 1.005 can’t be represented exactly in binary. The stored value is slightly less:

(1.005).toFixed(20) //'1.00499999999999989342'

toFixed() sees a number just under 1.005, so rounding down is correct from its point of view.

If you’re formatting money and these edge cases matter, don’t do arithmetic on decimal values at all. Keep amounts as integer cents (2120 instead of 21.20), do the math on integers, and divide by 100 only when displaying. Integers don’t have this precision problem, as long as you stay within the safe integer range.

For quick display formatting where being one cent off in rare edge cases is acceptable, toFixed() is fine, and it’s what I reach for.

~~~

Related posts about js: