一、浮点精度问题
浮点精度问题举例:
console.log(0.2+0.3);//0.5没有精度问题
console.log(0.1+0.2);//0.30000000000000004
console.log(0.1+0.7);//0.7999999999999999
console.log(0.2+0.4);//0.6000000000000001
console.log(0.3-0.2);//0.09999999999999998
console.log(1.5-1.2);//0.30000000000000004
console.log(35.41*100);//3540.9999999999995
console.log(19.9*100);//1989.9999999999998
console.log(0.3/0.1);//2.9999999999999996
1.产生原因
js数值型包含我们的整数 浮点数, ---Number 固定64位
int 16位
最高位--符号位 存储指数 尾数位--超出部分自动舍弃
1 11位 52位
0.1 二进制
0.0001100 1100 1100....(1100的循环)
0.2
0.0011001100110011.....(0011的循环)
0.1+0.2 相加后多余的会被舍弃,产生误差 js长度只截取64位
2.解决办法
0.1+0.2
(1)乘以10,再计算
(0.1*10+0.2*10)/10 //0.3
(2)toFixed() 截取位数,四舍五入
a=0.1+0.2
a.toFixed(1) //0.3
toFixed问题
console.log(1.35.toFixed(1));//1.4
console.log(1.334.toFixed(2));//1.33
console.log(1.335.toFixed(2));//1.33
console.log(1.336.toFixed(2));//1.34
console.log(1.3335.toFixed(3));//1.333
优化toFixed
方法1:
思路:将获取的小数转换为字符串 根据小数点的下标判断截取小数位数的下标
判断截取小数的后一位 四舍还是五入 对截取小数位进行操作
Number.prototype.mytoFixed=function(b){
var a = this.toString() //11.334
var c = (a.substring(0,a.indexOf(".")+1)).length //3
var num =String(a).substring(0,c-1+b)//11.3
if(String(a)[c+b] >= 5){
num = num + (Number(String(a)[c-1+b])+1)
}else{
num = num + (String(a)[c-1+b])
}
return num
}
var a = 11.334
console.log(a.mytoFixed(2))
方法2:
用toFixed获取需要截取位数的后面那一位,该位置上的数若等于5或者6,就让截取位上的数加1,否则返回正常的toFixed用法
Number.prototype.mytoFixed=function(num,n){
var a=num.toFixed(n+1)-num.toFixed(n)
var b=a.toFixed(n+1)*Math.pow(10,n+1)
if(b==5||b==6){
return (Number(num.toFixed(3))+Number(Math.pow(0.1,n).toFixed(n))).toFixed(n)
}else{
return num.toFixed(n)
}
}
var a=new Number().mytoFixed(1.335,2)
console.log(a)
方法3:
第三方库