Florian Gross
3/22/2005 9:34:00 PM
Arfin wrote:
> Is there some kind of class to format numbers? Something to let you
> transform:
>
> 1 => "0001"
"%04d" % 1
This is pretty much the same as sprintf() in C.
But in this case you can also do:
"1".rjust(4, "0")
> 1234 => "1,234.00"
I'd do that like this, even though there's other versions:
def number_format(number, padding_char = ",")
result = number.to_s
while pos = result.rindex(/\d{4}(?=\D|\Z)/)
result[pos + 1, 0] = padding_char
end
return result
end
irb(main):001:0> number_format 100_000_000
=> "100,000,000"
irb(main):002:0> number_format 10_000_000_000
=> "10,000,000,000"
irb(main):003:0> number_format "foo 10000000000 bar 50 qux 5000"
=> "foo 10,000,000,000 bar 50 qux 5,000"