js實現浮點數的加減乘除

//實現浮點數的加減乘除
/**

  • 3.2 + 4.32 = 7.52

  • 轉化爲:

  • 320 + 432 = 752

  • 752 / pow(10,2)
    */
    function add(a,b){
    let c,d,e,f,g;
    c = a.toString();
    d = b.toString();
    if(c.split(".")[1]){
    e = c.split(".")[1].length;
    }else{
    e = 0;
    }
    if(d.split(".")[1]){
    f = d.split(".")[1].length;
    }else{
    f = 0;
    }
    g = Math.max(e,f);

    return (a * Math.pow(10,g) + b*Math.pow(10,g)) / Math.pow(10,g)
    }
    /**

  • 3.45 - 1.21 = 2.24

  • 轉換爲:

  • 345 - 121 = 224

  • 224 / pow(10,2)
    */
    function sub(a,b){
    let c,d,e,f,g;
    c = a.toString();
    d = b.toString();
    if(c.split(".")[1]){
    e = c.split(".")[1].length;
    }else{
    e = 0;
    }
    if(d.split(".")[1]){
    f = d.split(".")[1].length;
    }else{
    f = 0;
    }
    g = Math.max(e,f);

    return (a * Math.pow(10,g) - b*Math.pow(10,g)) / Math.pow(10,g)
    }
    /**

  • 1.23 * 2 = 2.46

  • 轉換爲

  • 123 * 2 = 246

  • 246 / pow(10,2)
    /
    function mul(a,b){
    let c,d,e;
    c = a.toString();
    d = b.toString();
    if(c.split(".")[1]){
    e = c.split(".")[1].length;
    }else{
    e = 0;
    }
    if(d.split(".")[1]){
    e += d.split(".")[1].length;
    }
    return (Number(c.replace(".","")) * Number(d.replace(".",""))) / Math.pow(10,e)
    }
    /
    *

  • 2.42 / 2 = 1.21

  • 轉換爲

  • 242 / 2 = 121

  • 121 * pow(10,-2)
    */
    function div(a,b){
    let c,d,e,f;
    c = a.toString();
    d = b.toString();
    if(c.split(".")[1]){
    e = c.split(".")[1].length;
    }else{
    e = 0;
    }

    if(d.split(".")[1]){
    f = d.split(".")[1].length;
    }else{
    f = 0;
    }

    return (Number(c.replace(".","")) / Number(d.replace(".",""))) * Math.pow(10,f-e);

}
console.log(div(4.23,2))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章