可能重复:
ruby 中的算法
status_update模型在中取2个值,用它们进行一些简单的计算,并从中分配"current_lbm"one_answers"current_bf_pct"。
如果我不限制current_lbm和current_bf_pct,它们将产生大量的小数,所以我使用了.round(2)方法将值限制在小数点后2位。
这是实现这一点的方法。
after_initialize :default_values
.
.
def default_values
if self.current_bf_pct >= 0.5
self.current_bf_pct /= 100
if self.current_bf_pct <= 0.04
self.current_fb_pct *= 100
end
end
self.current_fat_weight = self.current_weight * self.current_bf_pct
self.current_lbm = self.current_weight - self.current_fat_weight
self.current_fat_weight = self.current_fat_weight.round(2)
self.current_lbm = self.current_lbm.round(2)
end
结果如下:
09/13/2012 186.0 4.5 177.63 8.37
09/13/2012 187.0 5.5 176.72 10.29
09/13/2012 188.0 6.5 175.78 12.22
09/13/2012 189.0 7.5 174.83 14.18
09/13/2012 190.0 8.5 173.85 16.15
09/13/2012 191.0 9.5 172.86 18.15
09/13/2012 192.0 10.5 171.84 20.16
09/13/2012 193.0 11.5 170.81 22.2
09/13/2012 194.0 12.5 169.75 24.25
09/13/2012 195.0 13.5 168.68 26.33
09/13/2012 196.0 14.499999999999998 167.58 28.42
09/13/2012 197.0 15.5 166.47 30.54
09/13/2012 198.0 16.5 165.33 32.67
09/13/2012 199.0 17.5 164.18 34.82
09/13/2012 200.0 18.5 163.0 37.0
我的问题是…14.499999999999998到底怎么了??
这些是视图的结果。current_bf_pct行是日期中的第三行。它们不是小数,因为我在视图中将它们乘以100。
如果按原样显示浮点,则无法避免这种情况(请参阅ruby中的算术)。我建议您将浮动转换为字符串进行显示。
示例(您的实际结果可能有所不同):
>> 7.3-7.2
=> 0.09999999999999964
转换为小数点后1位的字符串:
>> '%.1f' % (7.3-7.2)
=> "0.1"
"%"运算符是的缩写
sprintf '%.1f', (7.3-7.2)
阅读sprintf
。这是一个学习曲线,但它非常强大。
另一个解决方案是使用BigDecimal(第二个参数是精度-确保您理解这意味着什么):
BigDecimal(7.3-7.2, 1).to_s
如果你使用足够大的精度,你会再次看到问题:
>> BigDecimal(7.3-7.2, 16).to_s
=> "0.09999999999999964"