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?
Asked
Active
Viewed 4.2k times
5 Answers
81
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 "

the Tin Man
- 158,662
- 42
- 215
- 303
13
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
-
2A little broken. `1234567890.1234.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse => "1,234,567,890.1,234"` – Dean Brundage Nov 21 '14 at 15:08
7
You can use Kernel#sprintf
(or Kernel#format
) and do it that way. API Link.

Reese Moore
- 11,524
- 3
- 24
- 32
3
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 "

Chris
- 26,361
- 5
- 21
- 42

EMMANUEL OKELLO
- 169
- 1
- 15