Fixed number of digits after the decimal place with JavascriptFixed number of digits after the decimal place with Javascript

Posted August 11th, 2009 in 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+.

Number.toFixed(digits)

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:

1.10
1.12
1.12
1.13
1.1250

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.

Related posts:

Comments

blog comments powered by Disqus