format number with comma separators?

C

Chris Morris

I'm brain dead and just trying to get formatted numbers in a task that's
already 10 tangents deep -- argh. Anyway, how can I sprintf (or
otherwise) this:

456778904

to this:

456,778,904
 
M

Mark J. Reed

I'm brain dead and just trying to get formatted numbers in a task that's
already 10 tangents deep -- argh. Anyway, how can I sprintf (or
otherwise) this:

456778904

to this:

456,778,904

Unless there's something I don't know about - a distinct possibility
- there's no built-in function to do this. You can, however,
do it with a regex. Assuming the numbers are all integers (no
decimal points), then this will work:

formatted_n = n.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse

-Mark
 
R

Robert Klemme

Mark J. Reed said:
Unless there's something I don't know about - a distinct possibility
- there's no built-in function to do this. You can, however,
do it with a regex. Assuming the numbers are all integers (no
decimal points), then this will work:

formatted_n = n.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse

This fails for negative numbers in the range -100..-999 and all other
negative numbers with an amount of digits that is divisable by 3.

Alternative:

def format(num)
s = num.to_s

if s.include? ?.
pre, post = s.split '.'
"#{pre.reverse.gsub( /\d{3}(?=\d)/, '\&,' ).reverse}.#{post}"
else
s.reverse.gsub( /\d{3}(?=\d)/, '\&,' ).reverse
end
end

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top