ruby四舍五入到小数点后两位并保持零
我想在ruby中舍入一个最多两位小数的数字
(0.02 * 270187).round(2)
是5403.74,这是正确的
但
(0.02 * 278290).round(2)
是5565.8,与前一个不一致
我想让它看起来像5565.80
请告诉我如何在ruby中做到这一点
你可以做点什么
include ActionView::Helpers::NumberHelper number_with_precision(value, :precision => 2) # value.to_f if you have string
或者像这样
'%.2f' % your_value
希望能帮助到你! 您还可以从这里阅读
这样就可以了:
> sprintf("%.2f",(0.02 * 270187)) #=> "5403.74" > sprintf("%.2f",(0.02 * 278290)) #=> "5565.80" > sprintf("%.2f",(0.02 * 270187)).to_f > 100 # If you plan to Compare something with result #=> true
要么
> '%.2f' % (0.02 * 270187) #=> "5403.74" > '%.2f' % (0.02 * 278290) #=> "5565.80"
演示
注意:结果总是一个字符串,但是因为你正在四舍五入,所以我认为你是为了演示目的而做的。 sprintf几乎可以按照您喜欢的方式格式化任何数字。 如果您计划将此结果与任何内容进行比较,则通过在末尾添加.to_f
将此字符串转换为float。 像这样