Fixed number of digits after the decimal place with Javascript

As well as supporting various rounding functions, Javascript has the toFixed() method to have a specific number of digits after the decimal place. This function works in all modern browsers including Internet Explorer from 5.5+.


Simply pass the number of digits that should be after the decimal place and the string returned will be rounded to that number if there are more or zeros added if there are less.

Some examples:

document.write( 1.1.toFixed(2) + '<br>' );
document.write( 1.12.toFixed(2) + '<br>' );
document.write( 1.123.toFixed(2) + '<br>' );
document.write( 1.125.toFixed(2) + '<br>' );
document.write( 1.125.toFixed(4) + '<br>' );

These will write out to the document:


See also my rounding numbers with Javascript post for some other rounding methods which do not set a fixed number of digits after the decimal place.