- 十进制 二进制
- 0.1 0.0001 1001 1001 1001 …
- 0.2 0.0011 0011 0011 0011 …
- 0.3 0.0100 1100 1100 1100 …
- 0.4 0.0110 0110 0110 0110 …
- 0.5 0.1
- 0.6 0.1001 1001 1001 1001 …
所以比如 1.1,其程序实际上无法真正的表示 ‘1.1′,而只能做到一定程度上的准确,这是无法避免的精度丢失:1.09999999999999999
在JavaScript中问题还要复杂些,这里只给一些在Chrome中测试数据:
- console.log(1.0-0.9 == 0.1)
- console.log(1.0-0.8 == 0.2)
- console.log(1.0-0.7 == 0.3)
- console.log(1.0-0.6 == 0.4)
- console.log(1.0-0.5 == 0.5)
- console.log(1.0-0.4 == 0.6)
- console.log(1.0-0.3 == 0.7)
- console.log(1.0-0.2 == 0.8)
- console.log(1.0-0.1 == 0.9)
那如何来避免这类 1.0-0.9 != 0.1 的非bug型问题发生呢?下面给出一种目前用的比较多的解决方案, 在判断浮点运算结果前对计算结果进行精度缩小,因为在精度缩小的过程总会自动四舍五入:
- (1.0-0.9).toFixed(digits)
- console.log(parseFloat((1.0-0.9).toFixed(10)) === 0.1)
- console.log(parseFloat((1.0-0.8).toFixed(10)) === 0.2)
- console.log(parseFloat((1.0-0.7).toFixed(10)) === 0.3)
- console.log(parseFloat((11.0-11.8).toFixed(10)) === -0.8)
写成一个方法:
- function isEqual(number1, number2, digits){
- digits = digits == undefined? 10: digits;
- return number1.toFixed(digits) === number2.toFixed(digits);
- }
- console.log(isEqual(1.0-0.7, 0.3));
- Number.prototype.isEqual = function(number, digits){
- digits = digits == undefined? 10: digits;
- return this.toFixed(digits) === number.toFixed(digits);
- }
- console.log((1.0-0.7).isEqual(0.3));
接下来,再来试试浮点数的运算,
- console.log(1.79+0.12)
- console.log(2.01-0.12)
- console.log(1.01*1.3)
- console.log(0.69/10)
解决方案:
- function accAdd(arg1,arg2){
- var r1,r2,m;
- try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
- try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
- m=Math.pow(10,Math.max(r1,r2))
- return (arg1*m+arg2*m)/m
- }
- Number.prototype.add = function (arg){
- return accAdd(arg,this);
- }
-
- function accSub(arg1,arg2){
- var r1,r2,m,n;
- try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
- try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
- m=Math.pow(10,Math.max(r1,r2));
-
-
- n=(r1>=r2)?r1:r2;
- return ((arg1*m-arg2*m)/m).toFixed(n);
- }
- function accDiv(arg1,arg2){
- var t1=0,t2=0,r1,r2;
- try{t1=arg1.toString().split(".")[1].length}catch(e){}
- try{t2=arg2.toString().split(".")[1].length}catch(e){}
- with(Math){
- r1=Number(arg1.toString().replace(".",""))
- r2=Number(arg2.toString().replace(".",""))
- return (r1/r2)*pow(10,t2-t1);
- }
- }
- Number.prototype.div = function (arg){
- return accDiv(this, arg);
- }
-
- function accMul(arg1,arg2) {
- var m=0,s1=arg1.toString(),s2=arg2.toString();
- try{m+=s1.split(".")[1].length}catch(e){}
- try{m+=s2.split(".")[1].length}catch(e){}
- return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
- }
- Number.prototype.mul = function (arg){
- return accMul(arg, this);
- }
- <br>
- console.log(accAdd(1.79, 0.12));
- console.log(accSub(2.01, 0.12));
- console.log(accDiv(0.69, 10));
改造之后,可以愉快地进行浮点数加减乘除操作了~