Formatted output for numbers with comma's?

I was looking for a routine to convert a Number to a string with
comma’s, is there a routine in the library for that?

Wink

Wink Saville wrote:

I was looking for a routine to convert a Number to a string with
comma’s, is there a routine in the library for that?

http://rubyforge.org/snippet/detail.php?type=snippet&id=8

http://extensions.rubyforge.org/rdoc/classes/Numeric.html#M000011

http://globalize-rails.org/wiki/

On Mar 14, 2006, at 2:11 AM, Wink Saville wrote:

I was looking for a routine to convert a Number to a string with
comma’s, is there a routine in the library for that?

It’s not very hard to roll up a solution:

def commify( number )
number.to_s.reverse.gsub(/(\d\d\d)(?=\d)(?!\d*.)/, ‘\1,’).reverse
end

Hope that helps.

James Edward G. II

This would be a nice (ruby builtin) method :slight_smile:

def commify( number, positions)
positions = 3 if positions == nil
puts number.to_s.reverse.gsub(/(\d\d\d)(?=\d)(?!\d*.)/,
‘\1,’).reverse
^ not very sure how it would be done but something similar to
("\d"*positions)
end

puts commify(12345) # 12,345
puts commify(12345, 2) # 1,23,45

This would be a nice (ruby builtin) method :slight_smile:

+1 vote as I’ve needed it quite a bit.

How would I/we go about getting something like this in stdlib?

have fun,

SteveC [email protected] http://www.asklater.com/steve/

On 3/14/06, James Edward G. II [email protected] wrote:

On Mar 14, 2006, at 2:11 AM, Wink Saville wrote:

I was looking for a routine to convert a Number to a string with
comma’s, is there a routine in the library for that?

It’s not very hard to roll up a solution:

def commify( number )
number.to_s.reverse.gsub(/(\d\d\d)(?=\d)(?!\d*.)/, ‘\1,’).reverse
end

…it’s significantly harder to do it completely right, though.

See Gavin S.'s Extensions library in Numeric. I have a
relatively complete method written there, done in test-first style.

-austin