Monday, October 27, 2008

Humanize numbers with Ruby

Install
#config/initializers/numeric_humanize.rb

 1  class Numeric
2 def humanize(rounding=2,delimiter=',',separator='.')
3 value = respond_to?(:round_with_precision) ? round(rounding) : self
4
5 #see number with delimeter
6 parts = value.to_s.split('.')
7 parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{delimiter}")
8 parts.join separator
9 end
10 end

Usage:
puts 1.humanize
#=> 1
puts 1000000.humanize
#=> 1,000,000
puts 1000.12345.humanize
#=> 1,000.12345

No comments: