看下面的代码:

1
2
3
4
var n1:Number = 0.7;
var n2:Number = 0.4;
trace(n1 - n2);
//输出 0.29999999999999993

简单说,就是两个一位小数相减,差为何不是一位小数?

经测试,乘法也有同样的问题。

遛狗找到了Flex团队的一个回复(要翻墙):http://old.nabble.com/Float-number-calculation-in-AS3-td18447329.html

从回复看,AS3的Number与JAVA或C++的double类似,采用二进制分数而非十进制分数保存浮点部分,因此会导致不够精确。这是语言的设计思路所致。当然,从另一个思路看,它也是个BUG。

或许AS3引入double和float类型后会解决这个问题吧……

AS3’s Number type, like Java’s or C++’s ‘double’ type, store
floating-point values using binary fractions, not decimal fractions,
so
there is some loss of precision occuring. There is no
fractional-decimal
type in AS3.

I’ll leave it to folks in the developer community working on
financial
applications to explain how they work around this limitation.

Gordon Smith

Adobe Flex SDK Team

留言

2010-11-30
次访问