Formatting Decimals

Question: How do I format decimal numbers to a fixed number of decimal points (eg. only two digits after the decimal)?

Answer: Ruby, like C/C++, has a sprintf function. You can use that. Specify the parameter to format, and a string to indicate the number of decimal-points–for example:


avg = (10 + 8 + 7) / 3 # 7.66666666...
sprintf(avg, ".3f") # returns 7.667
sprintf(avg, ".0f") # returns 8

sprintf is useful for formatting a lot of things, not just decimals. You can find the API for it here.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

One Response to Formatting Decimals

  1. Andy says:

    You’ve mixed up the formatting string and the argument to be formatted. It’s the other way around: sprintf (format_string, arg)