How to format a string with floats in Ruby using #

2020-05-29 12:36发布

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
4条回答
够拽才男人
2楼-- · 2020-05-29 13:06

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-29 13:11

Yes, it's possible:

puts "Current amount: #{sprintf('%.2f', amount)}"
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-05-29 13:18

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"
查看更多
一夜七次
5楼-- · 2020-05-29 13:22

Use round:

"Current amount: #{amount.round(2)}"
查看更多
登录 后发表回答