Over a million developers have joined DZone.

Commify Numbers

·
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:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}