Does Ruby have any number formatting classes?

Does Ruby have any Formatter classes or methods that can be used to format numbers for things like currency, etc., or are there any gems that do this, or do you have to write you own?


Ruby has all the standard print formatters, available either via printf, sprintf or using 'formatstring' % [var1, ...].

>> '%.2f' % 3.14159 #=> "3.14"
>> '%4s %-4s' % ['foo', 'bar'] #=> " foo bar "

Try this:

1234567890.123.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
=> "1,234,567,890.123"

Taken from a comment by @pguardiario in a similar thread


You can use Kernel#sprintf (or Kernel#format) and do it that way. API Link.


Ruby provides Kernel#format class method that looks more like the python 3.x method. Checkout Ruby's Docs for more details. This can be used to format both string and number.There are others like %e and %g for exponential and etc.

Below are some examples.

number use %f for float and %d for integer

format('%.2f', 2.0) #=> "2.00"

format('%.d', 2.0) #=> "2"

string use %s

format('%.4s', "hello") #=> "hell"

format('%6s', "hello") #=> " hello"

format('%-6s', "hello") #=> "hello "