-1

诡异的..

$ (9.95*100).to_i
=> 994

接着,

$ (9.95*100).round.to_i
=> 995

浮点值似乎是(大约)9.9499999 ...和

to_i

砍掉十进制值,因此是 994。

但是有人知道为什么吗?

4

2 回答 2

3

Read more about the problems with accuracy here: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

Short version: Never use floats as representation for currencies.

于 2013-09-23T16:19:42.930 回答
0

您对 #round 的调用是从(其内部表示为 9.95,这是一个稍微不准确的数字,略低于它)“向上”四舍五入。这样就可以了,而直接调用 #to_i 只是(总是)截断,所以它看到 994.99999 并将其截断为 994。使用 Ruby 1.9.x+ 它更清楚地显示了这一点(无论好坏),所以你可以看到什么是继续。

>> 9.95*100
=> 994.9999999999999
>> (9.95*100).round
=> 995
于 2013-09-23T17:25:10.803 回答