Skip to content
All posts
·1 min read

To Fix JavaScript toFixed

The problem with the built in toFixed function in JavaScript, is that it always round the numbers. It’s like calling Math.round() Call 9.513.toFixed() => 10…

The problem with the built in toFixed function in JavaScript, is that it always round the numbers. It's like calling Math.round()
Call 9.513.toFixed() => 10
Call 9.226.toFixed(2) => 9.23
Why would you want that to auto round. If I wanted to round I would have round.

Not only that, the toFixed is not always rounding as expected.

Anyhow, here is how to do a toFixed accurately:

View the code on GitHub Gist

You can put it in the Number.prototype if you really want to, personally I rather put it in a untils object.

Comments (3)

Imported from the original blog

Giorgio BeggioraMar 13, 2018

this is bugged, see https://gist.github.com/guy...
this is way better: http://www.jacklmoore.com/n...

guyaMar 13, 2018

The link you gave is rounding the result. The point here is that there should be no rounding at all.
Check this link for more info:
https://stackoverflow.com/a...

Giorgio BeggioraMay 2, 2018

Docs says that "The number is rounded if necessary". See https://developer.mozilla.o... Plus, your implementation does not add zeroes when the decimal part is shorter than the "fixed" var. So, your function should be called "truncateTo" or similar, and not "toFixed".