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.
You can do this, but I prefer the
String#%
version: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
Yes, it's possible:
You can use
"#{'%.2f' % var}"
:Use
round
: