JS中浮点数运算精度问题解决
解决js⼩数运算精度问题
类似:0.1+0.2 = 0.30000000000000004;0.11 + 0.345 = 0.45499999999999996;
解决⽅法需要把⼩数转成整数运算完后在转成⼩数汤显祖的代表作
这边以0.11 + 0.345 = 0.45499999999999996;这个为例
代码
//判断⼩数点后有⼏位
let num1 =String().split(".")[1].length;//2
let num2 =String().split(".")[1].length;//3
let baNum =null;武汉有几个火车站
if( num1 > num2 ){//判断取⼩数点后位数多的那⼀个
融通汇信baNum = num1;
}el{
baNum = num2;
}
let sum =(~~(0.11*10** baNum))+(~~(0.345*10** baNum))
sum = sum /10** baNum;//0.455;
封装代码
const decimals=( num1,operationalCharacter,num2 )=>{
let num_1 = num1;
let num_2 = num2;
num1 = String().split(".")[1].length;//2
num2 = String().split(".")[1].length;//3
let baNum =null;
if( num1 > num2 ){//判断取⼩数点后位数多的那⼀个
baNum = num1;
}el{
baNum = num2;
}
let sum;
switch(operationalCharacter){
ca"+":
sum =(~~(num_1 *10** baNum))+(~~(num_2 *10** baNum));
break;
ca"-":
sum =(~~(num_1 *10** baNum))-(~~(num_2 *10** baNum));
break;
ca"*":
sum =(~~(num_1 *10** baNum))*(~~(num_2 *10** baNum));
break;
ca"/":
sum =(~~(num_1 *10** baNum))/(~~(num_2 *10** baNum));
break;
default:
break;
}
sum = sum /10** baNum;
return sum
};
export default decimals;
清蒸桂鱼做法// decimals( num1, operationalCharacter, num2 )
电饭煲炖鸡的做法// num1:运算数1
// operationalCharacter:运算符鹅蛋怎么做好吃
// num2:运算数2如何挽
益智类玩具// decimals(运算数1,运算符,运算数2)