JS计算浮点数问题

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>我的桌面</title>
</head>
<body>

<script type="text/javascript">  
    function add(a, b) {
        var c, d, e;
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
    }

    function sub(a, b) {
        var c, d, e;
        try {
            c = a.toString().split(".")[1].length;
        } catch (f) {
            c = 0;
        }
        try {
            d = b.toString().split(".")[1].length;
        } catch (f) {
            d = 0;
        }
        return e = Math.pow(10, Math.max(c, d)), (mul(a, e) - mul(b, e)) / e;
    }

    function mul(a, b) {
        var c = 0,
            d = a.toString(),
            e = b.toString();
        try {
            c += d.split(".")[1].length;
        } catch (f) {}
        try {
            c += e.split(".")[1].length;
        } catch (f) {}
        return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
    }

    function div(a, b) {
        var c, d, e = 0,
            f = 0;
        try {
            e = a.toString().split(".")[1].length;
        } catch (g) {}
        try {
            f = b.toString().split(".")[1].length;
        } catch (g) {}
        return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
    }
      
</script>  
    
<script>  
    document.write("使用js原生态方法");  
    document.write("<br/> 1.01 + 1.02 ="+(1.01 + 1.02));  
    document.write("<br/> 1.01 - 1.02 ="+(1.01 - 1.02));  
    document.write("<br/> 0.000001 / 0.0001 ="+(0.000001 / 0.0001));  
    document.write("<br/> 0.012345 * 0.000001 ="+(0.012345 * 0.000001));  
    document.write("<br/><hr/>");  
    document.write("<br/>使用自定义方法");  
    document.write("<br/> 1.01 + 1.02 ="+add(1.01,1.02));  
    document.write("<br/> 1.01 - 1.02 ="+sub(1.01,1.02));  
    document.write("<br/> 0.0000015 / 0.0004 ="+div(0.0000015,0.0004));  
    document.write("<br/> 0.012345 * 0.000001 ="+mul(0.012345,0.000001));  


    console.log(45.1/2);
    console.log(45.11/2);
    console.log(45.12/2);
    console.log(45.13/2);
    console.log(45.14/2);
    console.log(45.15/2);
    console.log(45.16/2);
    console.log(45.17/2);
    console.log(45.18/2);
    console.log(45.19/2);
    console.log(45.2/2);
    console.log(45.3/2);
    console.log(45.4/2);
    console.log(45.5/2);
    console.log(45.6/2);
    console.log(45.7/2);
    console.log(45.8/2);
    console.log(45.9/2);

</script>  
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/wangzijoe/p/9087799.html