def commify(number) c = { :value => "", :length => 0 } r = number.to_s.reverse.split("").inject(c) do |t, e| iv, il = t[:value], t[:length] iv += ',' if il % 3 == 0 && il != 0 { :value => iv + e, :length => il + 1 } end r[:value].reverse! end
Alex Young suggested
def commify(v) (s=v.to_s;x=s.length;s).rjust(x+(3-(x%3))).scan(/.{3}/).join(',').strip end
and there's always
number_with_delimiter(number, delimiter)
from NumberHelper in the Rails API ... which is implemented as follows:-
def number_with_delimiter(number, delimiter=",") number.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}") end
They don't always work too well when the number has a decimal point in it (and more than two or so digits after the decimal point), so there's room for an improved version ...
JV suggested the following snippet from http://pleac.sourceforge.net/pleac_ruby/numbers.html which appears to be able to handle commas and decimal places as well.
def commify(n) n.to_s =~ /([^\.]*)(\..*)?/ int, dec = $1.reverse, $2 ? $2 : "" while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3') end int.reverse + dec end