From: Phrogz Date: 2006-11-26T01:55:07+09:00 Subject: Re: Formating Floats as Money John Kopanas wrote: > I have a number that is of type float. I want to format it as dollars > and cents. How do you recommend I do it? :-) Here's my shot at it: class Numeric def to_currency( pre_symbol='$', thousands=',', decimal='.', post_symbol=nil ) "#{pre_symbol}#{ ( "%.2f" % self ).gsub( /(\d)(?=(?:\d{3})+(?:$|\.))/, "\\1#{thousands}" ) }#{post_symbol}" end end [ 1,21,321,4321,54321,654321,7654321,87654321, 1.5,21.5,321.5,4321.5,54321.5,654321.5, ].each{ |n| puts "%14s -> %s" % [ n.to_s, n.to_currency ] puts "%14s -> %s" % [ (-n).to_s, (-n).to_currency ] } #=> 1 -> $1.00 #=> -1 -> $-1.00 #=> 21 -> $21.00 #=> -21 -> $-21.00 #=> 321 -> $321.00 #=> -321 -> $-321.00 #=> 4321 -> $4,321.00 #=> -4321 -> $-4,321.00 #=> 54321 -> $54,321.00 #=> -54321 -> $-54,321.00 #=> 654321 -> $654,321.00 #=> -654321 -> $-654,321.00 #=> 7654321 -> $7,654,321.00 #=> -7654321 -> $-7,654,321.00 #=> 87654321 -> $87,654,321.00 #=> -87654321 -> $-87,654,321.00 #=> 1.5 -> $1.50 #=> -1.5 -> $-1.50 #=> 21.5 -> $21.50 #=> -21.5 -> $-21.50 #=> 321.5 -> $321.50 #=> -321.5 -> $-321.50 #=> 4321.5 -> $4,321.50 #=> -4321.5 -> $-4,321.50 #=> 54321.5 -> $54,321.50 #=> -54321.5 -> $-54,321.50 #=> 654321.5 -> $654,321.50 #=> -654321.5 -> $-654,321.50