47

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?

ab217
  • 16,900
  • 25
  • 74
  • 92

5 Answers5

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

Community
  • 1
  • 1
ynkr
  • 25,946
  • 4
  • 32
  • 30
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
0

You can check out the ActionView::Helpers::NumberHelper in Rails' ActionView gem.

Alexander
  • 59,041
  • 12
  • 98
  • 151
Toby
  • 2,039
  • 1
  • 13
  • 10