2017年6月18日 星期日

四則運算

因為 javascript 算術有誤差,主要是有小數點時,但整數不會,所以做法是先轉成整數後再恢復,但有可能進來的小數點位數不確定,所以寫程動態的方式


<script>
'use strict'
    window.onload = () => {
        Number.prototype.plus = function (param){ 
            return accessPlus(this, param); 
        }
    
        Number.prototype.substract = function (param){ 
            return accessSubstract(this, param); 
        }
    
        Number.prototype.multiply = function (param){ 
            return accessMultiple(this, param); 
        }
    
        Number.prototype.divide = function (param){ 
            return accessDivide(this, param); 
        }
    
        /*
         無條件捨去到n位,由於內鍵的Math.floor並沒有小數點的部分,所以加這一支
        */
        Math.floorDecimal = function (value, param){
            let temp = Math.pow(10, param);
            return Math.floor(value * temp)/temp;
        }
    
        // alert(accessDivide(7, 0.35));
        // alert(accessSubstract(n1, n2));
        // alert(accessMultiple(7, 1.35));
        // alert(accessPlus(n1, n2));
    
        let n1 = 7;
        let n2 = 1.35;
        alert(n1.plus(n2));
        alert(n1.substract(n2));
        alert(n1.multiply(n2));
        alert(n1.divide(n2));
        alert(Math.floorDecimal(2.12345679, 6));
    }
    
    let utilArithmetic = (p1, p2) => {
        // 轉字串
        let sp1 = p1.toString();
        let sp2 = p2.toString();
    
        // 小數點後的數字
        let sp1Split = sp1.split(".")[1];
        let sp2Split = sp2.split(".")[1];
    
        // 回傳小數點後的數字長度
        let len1 = typeof(sp1Split) == 'undefined' ? 0 : sp1Split.length;
        let len2 = typeof(sp2Split) == 'undefined' ? 0 : sp2Split.length;
    
        // 將小數點移除
        let np1 = Number(sp1.replace(".", ""));
        let np2 = Number(sp2.replace(".", ""));
    
        return {'len1':len1, 'len2':len2, 'np1':np1, 'np2':np2};
    }
    
    let accessPlus = (p1, p2) => { 
        let json = utilArithmetic(p1, p2);
        let pow = Math.pow(10, Math.max(Number(json.len1), Number(json.len2)));
        return (p1 * pow + p2 * pow) / pow;
    }
    
    let accessSubstract = (p1,p2) => {
        let json = utilArithmetic(p1, p2);
        let max = Math.max(Number(json.len1), Number(json.len2));
        let pow = Math.pow(10, max);
        return ((p1 * pow - p2 * pow) / pow).toFixed(max);
    } 
    
    let accessMultiple = (p1, p2) => {
        let json = utilArithmetic(p1, p2);
        return json.np1 * json.np2 / Math.pow(10, json.len2+json.len1);
    }
    
    let accessDivide = (p1, p2) => {
        let json = utilArithmetic(p1, p2);
        return json.np1 / json.np2 * Math.pow(10, json.len2-json.len1);
    }
</script>



沒有留言:

張貼留言