如何使用#{variable} 在 Ruby 中格式化带有浮点数的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12389567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:25:31  来源:igfitidea点击:

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

ruby

提问by marcotama

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.

我想获得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.

但我在问是否有可能以这种#{}方式做到这一点。

采纳答案by Bjoernsen

Use round:

使用round

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

回答by Spajus

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

您可以使用"#{'%.2f' % var}"

irb(main):048:0> num = 3.1415
=> 3.1415
irb(main):049:0> "Pi is: #{'%.2f' % num}"
=> "Pi is: 3.14"

回答by Michael Kohl

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

你可以这样做,但我更喜欢这个String#%版本:

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

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

正如@Bjoernsen 指出的那样,round是最直接的方法,它也适用于标准 Ruby (1.9),而不仅仅是 Rails:

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

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

回答by Lukas Stejskal

Yes, it's possible:

是的,这是可能的:

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