Browse | Submit A New Snippet | Create A Package

 

Commify a Number

Type:
Function
Category:
Math Functions
License:
Ruby License
Language:
Ruby
 
Description:
A convenient function to commify a number or number string using Tom Copeland's snippet. Examples:

irb(main):009:0> commify(123456)
=> "123,456"
irb(main):010:0> commify('123456')
=> "123,456"
irb(main):011:0> commify('123456','_')
=> "123_456"
irb(main):012:0> commify(123456,'_')
=> "123_456"

Versions Of This Snippet::

Kurt Stephens
Snippet ID Download Version Date Posted Author Delete
2762.02007-09-18 15:59Kurt Stephens
Changes since last version::
Much simpler.
1451.12006-04-14 22:21Craig Kim
Changes since last version::
Make it an object method.
1441.02006-04-09 02:44Craig Kim

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :2.0

class Object
  def commify(sep = ',')
    to_s.
      reverse.
      gsub!(/\d{3}/){|x| x + sep}.
      reverse!.
      sub!(/^#{sep}/, '')
  end
end

puts "1234".commify
puts 123.commify('_')
puts 123456.commify


		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..