看下面代码运行结果:
trace(256.08+123.1); //379.17999999999995 trace(256.08-123.11); //132.96999999999997 trace(8.4*0.112); //0.9408000000000001
AS3的Number与JAVA或C++的double类似,采用二进制分数而非十进制分数保存浮点部分,因此会导致不够精确。这是语言的设计思路所致。当然,从另一个思路看,实际上它就是个BUG。
为了必须定需求,只好曲线救国:
/** * 解决计算Number数据不精确问题 * @param n1 值1 * @param n2 值2 * @param operation 运算符 (+ - * )除法应该不存在这个问题; */ function numberCalculate(n1:Number,n2:Number,operation:String):Number { var len1:int = getNumberFixed(n1); var len2:int = getNumberFixed(n2); var len:int = Math.max(len1,len2); var s:String = "1"; for (var i:int = 0; i<len; i++) { s += "0"; } var level:int = int(s); var result:Number; switch (operation) { case "+" : result = (n1*level+n2*level)/level; break; case "-" : result = (n1*level-n2*level)/level; break; case "*" : result = ((n1*level)*(n2*level))/(level*level); break; } return result; } /** * 获取Number数值的小数位数 * return int */ function getNumberFixed(n:Number):int { var s:Array = n.toString().split("."); if (s.length == 2) { return s[1].length; } return 0; }
测试结果:
trace(numberCalculate(256.08,123.1,"+")); //379.18 trace(numberCalculate(256.08,123.11,"-")); //132.97 trace(numberCalculate(8.4,0.112,"*")); //0.9408