js ES6 加减乘除法小数浮点数计算BUG解决

//检测是否为数字

let num = (a) => {

    if(a != null && a.toString() != "") {

        let r = /^-?(0|[1-9]+\d*|[1-9]+\d*\.\d+|0\.\d+)$/;

        if(r.test(a.toString())) {

            return true;

        }

    }

    return false;

}

//加法

let plus = (a, b) => {

    if(!num(a) || !num(b)) {

        return null;

    }

    let c, d, m;

    try {

        c = a.toString().split(".")[1].length;

    } catch(e) {

        c = 0;

    }

    try {

        d = b.toString().split(".")[1].length;

    } catch(e) {

        d = 0;

    }

    m = Math.pow(10, Math.max(c, d));

    return(a * m + b * m) / m;

}

//减法

let minus = (a, b) => {

    if(!num(a) || !num(b)) {

        return null;

    }

    let c, d, m, n;

    try {

        c = a.toString().split(".")[1].length;

    } catch(e) {

        c = 0;

    }

    try {

        d = b.toString().split(".")[1].length;

    } catch(e) {

        d = 0;

    }

    m = Math.pow(10, Math.max(c, d));

    return(a * m - b * m) / m;

// n = (c >= d) ? c : d;

// return((a * m - b * m) / m).toFixed(n);//数字转换字符串,保留n位小数

}

//乘法

let multiply = (a, b) => {

    let m = 0,

    c = a.toString(),

    d = b.toString();

    try {

        m += c.split(".")[1].length

    } catch(e) {}

    try {

        m += d.split(".")[1].length

    } catch(e) {}

    return Number(c.replace(".", "")) * Number(d.replace(".", "")) / Math.pow(10, m)

}

//除法

let division = (a, b) => {

    if(!num(a) || !num(b)) {

        return null;

    }

    let c, d, f, g;

    try {

        c = a.toString().split(".")[1].length;

    } catch(e) {

        c = 0;

    }

    try {

        d = b.toString().split(".")[1].length;

    } catch(e) {

        d = 0;

    }

    with(Math) {

        f = Number(a.toString().replace(".", ""));

        g = Number(b.toString().replace(".", ""));

        return(f / g) * pow(10, d - c);

    }

}

猜你喜欢

转载自my.oschina.net/af666/blog/1630557