前端JS

1.json对象可进行for循环遍历

for(var obj in jsonObj){

  alert(jsonObj[obj]);

}

2.最近在前端使用JS进行浮点数计算时,发现JS并不怎么支持数计算

12.36+56.39

例如以上这种,可能算出来的数据跟我们想象中的有偏差(并非所有数据都会出现这个情况)

通过查看网上资料,有以下方案:

将浮点数乘以10的N次方转换成整型数,然后在相加,最后除以10的N次方转换成浮点数

本来以为OK,大部分测试数据都可行。

但是还是有部分数据

例如:123.01*100,最终结果可能不是我们想要的12301,而是12301.00000000000004这类,这说明了JS不仅仅不支持浮点数相加,包括整乘或者zhe整除都不支持。

最后只有通过十进制原理和字符串结合重新写了两个浮点数相加的算法

function addFloat(floatValue1,floatValue2){
    //获取浮点数精度
    var accuracy1 = floatValue1.indexOf(".")==-1?0:floatValue1.indexOf(".");
    var accuracy2 = floatValue2.indexOf(".")==-1?0: floatValue2.indexOf(".");
    //定义最大精度
    var maxAccuracy = accuracy1 >accuracy2?accuracy1 :accuracy2;
    floatValue1=floatValue1.replace(".","");  
    floatValue1=floatValue2.replace(".","");

    //获取精度差,保证去点后两浮点数整乘倍数一致
    var count = accuracy2-accuracy1;
    while(count!= 0){
        count>0?(accuracy1+="0"):(accuracy2+="0");
        count>0?count--:count++;
    }
    //将整乘后的数字相加并转换成字符串
    var totalInt = parseInt(floatValue1,10)+parseInt(floatValue2,10)+"";
    //符号补零处理,例如2.01+(-1.97)=0.04,整乘后为4,最后需要转回0.04
    if(totalInt.indexOf("-")==-1){
        var count1=maxAccuracy-totalInt.length;
        while(count1!=0){
            totalInt="0"+totalInt;
            count1--;
        }
    }else{
        var count2=maxAccuracy-totalInt.length+1;
        while(count2!=0){
            totalInt=totalInt.substr(0,1)+"0"+totalInt.substr(1);
            count2--;
        }
    }
    return totalInt.substr(0,totalInt.length-maxAccuracy)+"."+totalInt.substr(totalInt.length-maxAccuracy);
}
    }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值