DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jonathan has posted 1 posts at DZone. View Full User Profile

Format number with thousands separator

10.01.2013
| 4309 views |
  • submit to reddit
def format_with_separator(number)
  whole_part, decimal_part = number.to_s.split('.')
  [whole_part.gsub(/(\d)(?=\d{3}+$)/, '\1,'), decimal_part].compact.join('.')
end

This gsub call provides a concise way to add thousands separators to numeric values. If you know what kinds of numbers you expect, you can simplify this even more, but for public consumption, I wanted to allow for both integers and decimal numbers of any kind.

As another example, if you're actually formatting currencies, and know you always want two decimal places, you can simply use

sprintf("%0.2f", number).gsub(/(\d)(?=\d{3}+\.)/, '\1,')

If you were formatting with no decimal places, you would use `$` or `\Z` instead of the `\.`, like

sprintf("%d", number).gsub(/(\d)(?=\d{3}+$)/, '\1,')