处理js小数精度计算问题

//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
    
}

  

posted @ 2022-12-14 09:14  南瓜壳  阅读(68)  评论(0编辑  收藏  举报