Actionscript3的Number类型计算精度问题

本站原创文章,转载请注明: 转载自zrong's Blog,原文 Actionscript3的Number类型计算精度问题

本站转载文章会标明[转],转载请注明原始作者文章地址。



看下面的代码:
?[Copy to clipboard] View Code ACTIONSCRIPT
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

AS3

一般数据不大而要求精度较高时,可以先将Number转成int类型计算,然后再转成Number。但对于int范围以外的数据来说这种方法当然是不可取的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值