Never been to DZone Snippets before?

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

Turn numbers into strings with thousands' separators (See related posts)

Turn numbers into strings with thousands' separators (from zenspider)

class Numeric
  def commify(dec='.', sep=',')
    num = to_s.sub(/\./, dec)
    dec = Regexp.escape dec
    num.reverse.gsub(/(\d\d\d)(?=\d)(?!\d*#{dec})/, "\\1#{sep}").reverse
  end
end


So, you get:

1233232423424.23423.commify # => "1,233,232,423,424.23"

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts