如何使用#{variable} 在 Ruby 中格式化带有浮点数的字符串? [英] How to format a string with floats in Ruby using #{variable}?

查看:48
本文介绍了如何使用#{variable} 在 Ruby 中格式化带有浮点数的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化一个包含浮点变量的字符串,其中包括固定数量的小数,我想用这种格式语法来做:

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}"

我想获得当前数量:3.14.

我知道我可以用

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

但我在问是否可以用 #{} 方式做到这一点.

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

推荐答案

使用 ​​round:

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

这篇关于如何使用#{variable} 在 Ruby 中格式化带有浮点数的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆