Fixed 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:
- parseInt('08') returns 0 with Javascript (Friday, February 19th 2010)
- Rounding numbers with Javascript (Tuesday, May 5th 2009)
- Pad a number with leading zeroes in Javascript - Improved (Friday, May 1st 2009)
- Format a date time in Javascript in database format (Friday, April 24th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

