2

我是 Ruby 的新手,所以我首先为我的无知道歉 :) 我在汇总客户帐户时发现了一个问题。一些金额在小数点后为负数,这会破坏总数。这是一些简单的示例代码...

testnum = 0.00
puts "###Debug### testnum = #{testnum} (after  0.00)"
testnum += 5.00
puts "###Debug### testnum = #{testnum} (after  5.00)"
testnum += 3.33
puts "###Debug### testnum = #{testnum} (after  3.33)"
testnum += -1.00
puts "###Debug### testnum = #{testnum} (after -1.00)"
testnum += -2.22
puts "###Debug### testnum = #{testnum} (after -2.22)"

结果...

###Debug### testnum = 0.0 (after  0.00)
###Debug### testnum = 5.0 (after  5.00)
###Debug### testnum = 8.33 (after  3.33)
###Debug### testnum = 7.33 (after -1.00)
###Debug### testnum = 5.109999999999999 (after -2.22)

所以添加-2.22后testnum被破坏了,但是添加-1.00就可以了。不知道我做错了什么。

4

2 回答 2

2

来自http://floating-point-gui.de/basic/

为什么我的数字,比如 0.1 + 0.2 加起来不是很好的 0.3 轮,而是得到一个奇怪的结果,比如 0.30000000000000004?

因为在内部,计算机使用的格式(二进制浮点)根本无法准确表示 0.1、0.2 或 0.3 之类的数字。

如果您确实需要将结果精确地相加,尤其是在使用金钱时:使用特殊的十进制数据类型。

在 Ruby 中,这是BigDecimal

于 2012-11-08T11:05:14.453 回答
1

恐慌上校的推理是正确的,我不想重复同样的,另外你可以使用圆形功能。例如:

1.9.3p194 :001 > 5.109999999999999.round(2)
 => 5.11 

因为您最多只使用 2 个十进制数字,所以这对您应该很有用

于 2012-11-08T14:47:40.740 回答