Sep 18, 2008

[RUBY] Formating numbers with commas

I want to format the numbers with commas, there maybe a better way to do it, but this one works for me:

  # Return String formated as "123,456.78"
def format_number(number)
  s = "%0.2f" % number
  s =~ /([^\.]*)(\..*)?/
 int, dec = $1, $2
 int.gsub(/(\d)(?=\d{3}+(\.\d*)?$)/, '\1,') + dec
end

No comments: