JavaScript中var、let和const的区别_我亦飘零久-O-的博客-CSDN博客
js number类型运算都需要先将十进制转二进制,但小数点后的位数转二进制会出现无限循环的问题,只能舍0入1,所以会出现小数点丢失问题
解决方法
//num1 num2传入两个值 symbol +-*/符号
function amend(num1,num2,symbol){
var str1=num1.toString(),str2=num2.toString(),result,str1Length,str2Length
//解决整数没有小数点方法
try {str1Length= str1.split('.')[1].length} catch (error) {str1Length=0}
try {str2Length= str2.split('.')[1].length} catch (error) {str2Length=0}
var step=Math.pow(10,Math.max(str1Length,str2Length))
//
console.log(step);
switch (symbol) {
case "+":
result= (num1*step+num2*step)/step
break;
case "-":
result= (num1*step-num2*step)/step
break;
case "*":
result= ((num1*step)*(num2*step)) / step/step
break;
case "/":
result= (num1*step)/(num2*step)
break;
default:
break;
}
return result
}
console.log(amend(0.1,0.2,"+"));