Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Commify Numbers

DZone's Guide to

Commify Numbers

·
Free Resource
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", ".")


Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}