From: John Kaurin Date: 2001-11-03T13:09:00+09:00 Subject: [ruby-talk:24247] Re: Thousand Separator "Wai-Sun Chia" wrote in message news:3BE0D1C6.7090703@msa.dec.com... | Hello, | I'm in the need of a thousand separator method which takes in a number | and spits it back out nicely separated with the current locale's | thousand separator (',' in my case). | | This is something like PHP's number_format() or printf()'s '%'f'... | Anybody did something like this? | | | | | -- | Wai-Sun "Squidster" Chia | RHCE/Professional Services | Linux/Unix/Web Developer | | Here is a thought starter, not very robust. def commafy(number) # Reverse the digits that make up the number to ease processing. number = number.to_s.reverse # Add commas in the appropriate places. number.gsub!(/(\d\d\d)(?=\d)(?!\d*\.)/) do |match| $1 + ',' end # Reverse the result back to the proper form. number = number.to_s.reverse end puts commafy(100000000) # => 100,000,000 puts commafy(100000.01) # => 100,000.01 puts commafy(-10000000) # => -10,000,000 puts commafy(-10000.00) # => -10,000.0 puts commafy(123456.70) # => 123,456.7 puts commafy(123.45600) # => 123.456 puts commafy(123.45e10) # => 1.2345e+12 puts commafy(1234.5e10) # => 1.2345e+13 puts commafy(1234.5067) # => 1,234.5067 puts commafy(1.2345678) # => 1.2345678 puts 123.4560.to_s # => 123.456 puts 123.4560.to_a # => 123.456