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

Snippets has posted 5883 posts at DZone. View Full User Profile

Commify Numbers

02.17.2006
| 5861 views |
  • submit to reddit
        This is just the Ruby version of a known regular expression
to get comma-formatted numbers.


numbers = "10000000 1.345 -91245555.45 +6788876.224334 -2321232" 

numbers.reverse!

#numbers.gsub!(/(\d\d\d)(?=\d)(?!\d*\.)/, '\1,')
numbers.gsub!(%r{([[:digit:]]{3})(?=[[:digit:]])(?![[:digit:]]*\.)}, '\1,')

puts numbers.reverse!


#--------------------------


# cf. http://www.misuse.org/science/2008/03/27/converting-numbers-or-currency-to-comma-delimited-format-with-ruby-regex/
# http://extensions.rubyforge.org/rdoc/classes/Numeric.html#M000011

def format_num(num, delim = ',')
  num.to_s.reverse.gsub(%r{([[:digit:]]{3})(?=[[:digit:]])(?![[:digit:]]*\.)}, "\\1#{delim}").reverse
end

puts format_num(1000)
puts format_num(123456.78)
puts format_num("$12345")
puts format_num("123456", ".")