How to format a string with floats in Ruby using #{variable}?

Ruby

Ruby Problem Overview


I would like to format a string containing float variables including them with a fixed amount of decimals, and I would like to do it with this kind of formatting syntax:

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

and I would like to obtain Current amount: 3.14.

I know I can do it with

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

but I am asking if it is possible to do it in the #{} way.

Ruby Solutions


Solution 1 - Ruby

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"

Solution 2 - Ruby

Use round:

"Current amount: #{amount.round(2)}"

Solution 3 - Ruby

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

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

As @Bjoernsen pointed out, round is the most straightforward approach and it also works with standard Ruby (1.9), not only Rails:

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

Solution 4 - Ruby

Yes, it's possible:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcotamaView Question on Stackoverflow
Solution 1 - RubySpajusView Answer on Stackoverflow
Solution 2 - RubyBjoernsenView Answer on Stackoverflow
Solution 3 - RubyMichael KohlView Answer on Stackoverflow
Solution 4 - RubyLukas StejskalView Answer on Stackoverflow