js中在执行加减乘除运算时候会造成如下问题
0.1+0.2===0.3 //false
0.1+0.2=0.30000000000000004
0.6+0.7===1.3 //false
0.6+0.7=1.2999999999999998
下面通过特殊处理解决这一问题
* 在原型写方法
* 先将浮点数转为整数运算
*
*/
Number.prototype.addFloat=function(num2){
var num1=this;
return handleFloat.add(num1,num2)
}
Number.prototype.subtractFloat=function(num2){
var num1=this;
return handleFloat.subtract(num1,num2)
}
Number.prototype.multipleFloat=function(num2){
var num1=this;
return handleFloat.multiple(num1,num2)
}
Number.prototype.divideFloat=function(num2){
var num1=this;
return handleFloat.divide(num1,num2)
}
var handleFloat={
/**
* 加法
* @param {*} num1
* @param {*} num2
*/
add:function(num1,num2){
let pow=handleFloat._getPointPow(num1,num2);
return (num1*pow+num2*pow)/pow
},
/**
* 减法
* @param {*} num1
* @param {*} num2
*/
subtract:function(num1,num2){
let pow=handleFloat._getPointPow(num1,num2);
return (num1*pow-num2*pow)/pow
},
/**
* 乘法
* @param {*} num1
* @param {*} num2
*/
multiple:function(num1,num2)
{
let pow=handleFloat._getPointPow(num1,num2);
return ((num1*pow)*(num2*pow))/(pow*pow)
},
/**
* 除法
* @param {*} num1
* @param {*} num2
*/
divide:function(num1,num2){
let pow=handleFloat._getPointPow(num1,num2);
return ((num1*pow)/(num2*pow))
},
/**
* 获取两个数小数点的长度最大值,然后取10的次幂
* @param {*} num1
* @param {*} num2
*/
_getPointPow:function(num1,num2){
if(typeof num2!=='number')
{
throw new TypeError('数字不合法');
}
let pointLength1=0,pointLength2=0;
//如果存在小数点
if((num1+'').indexOf('.')){
pointLength1=(num1+'').split('.')[1].length;
}
if((num2+'').indexOf('.')){
pointLength2=(num2+'').split('.')[1].length;
}
return Math.pow(10,Math.max(pointLength1,pointLength2));
}
}
测试
console.log(0.1.addFloat(0.2)); //0.3
console.log(0.6.addFloat(0.7)); //1.3
console.log(0.1.addFloat('s')); //0.5 // typeError
console.log(0.1.subtractFloat(0.2)); //-0.1
console.log(0.1.multipleFloat(0.2)); //0.02
console.log(0.1.divideFloat(0.2)); //0.5
网友评论