How to format string using float in Ruby using # {variable}?

I would like to format a string containing float variables, including them with a fixed number of decimal places, and I would like to do this using this formatting syntax:

amount = Math::PI puts "Current amount: #{amount}" 

and I would like to receive Current amount: 3.14 .

I know I can do it with

 amount = Math::PI puts "Current amount %.2f" % [amount] 

but I ask if this can be done with #{} .

+46
ruby
Sep 12 2018-12-12T00:
source share
4 answers

Use round :

 "Current amount: #{amount.round(2)}" 
+39
Sep 12
source share

You can use "#{'%.2f' % var}" :

 irb(main):048:0> num = 3.1415 => 3.1415 irb(main):049:0> "Pi is: #{'%.2f' % num}" => "Pi is: 3.14" 
+40
Dec 23 '13 at 8:34
source share

You can do this, but I prefer the version of String#% :

  puts "Current amount: #{format("%.2f", amount)}" 

As @Bjoernsen pointed out, round is the easiest approach, it also works with standard Ruby (1.9), not just Rails:

http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round

+32
Sep 12
source share

Yes, it is possible:

 puts "Current amount: #{sprintf('%.2f', amount)}" 
+5
Sep 12
source share



All Articles