Jul 12
There are a lot of posts out there about how to add commas to numbers, but I haven’t seen any that showed how to make it a method of the built-in number types. Its very easy actually, but for those who are beginner Rubyists, here’s how I did it:
class Bignum
def commas
self.to_s =~ /([^\.]*)(\..*)?/
int, dec = $1.reverse, $2 ? $2 : ""
while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
end
int.reverse + dec
end
end
class Float
def commas
self.to_s =~ /([^\.]*)(\..*)?/
int, dec = $1.reverse, $2 ? $2 : ""
while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
end
int.reverse + dec
end
end
class Fixnum
def commas
self.to_s =~ /([^\.]*)(\..*)?/
int, dec = $1.reverse, $2 ? $2 : ""
while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
end
int.reverse + dec
end
end
Its the same function added to the three main number classes(Bignum, Float, and Fixnum). You would use them like so:
irb(main):001:0> require 'exo/format' => true irb(main):002:0> g = 123456789 => 123456789 irb(main):003:0> g.commas => "123,456,789" irb(main):004:0> f = 123456.7891 => 123456.7891 irb(main):005:0> f.commas => "123,456.7891" irb(main):006:0> b = 12347862389461237846192873461287346 => 12347862389461237846192873461287346 irb(main):007:0> b.commas => "12,347,862,389,461,237,846,192,873,461,287,346" irb(main):008:0>
(exo/format is just the filename I use for the code above) These methods have the added benefit of converting the number into a string so you don’t have to convert before printing out.






