ruby四舍五入到小数点后两位并保持为零

时间:2015-11-19 11:03:34

标签: ruby-on-rails ruby rounding

我想在ruby中将一个小数位数加到小数点后两位

(0.02 * 270187).round(2)是5403.74,这是正确的

但是

(0.02 * 278290).round(2)为5565.8,与之前的

不一致

我想让它看起来像5565.80

请告诉我如何在ruby中进行操作

2 个答案:

答案 0 :(得分:5)

您可以执行类似

的操作
include ActionView::Helpers::NumberHelper

number_with_precision(value, :precision => 2) # value.to_f if you have string

或者像这样

'%.2f' % your_value

希望它有所帮助! 您还可以阅读here

答案 1 :(得分:5)

这样可以解决问题:

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

Demo

注意:结果始终是一个字符串,但是由于你正在进行四舍五入,我认为无论如何你都是为了演示而做的。 sprintf 几乎可以按您喜欢的方式格式化任意数字。如果您计划将此结果与任何内容进行比较,则通过在末尾添加.to_f将此字符串转换为float。的 Like this