龙空技术网

js的加减乘除计算

小小的白 430

前言:

当前姐妹们对“js计算和”大概比较关怀,咱们都需要分析一些“js计算和”的相关文章。那么小编在网摘上网罗了一些有关“js计算和””的相关内容,希望你们能喜欢,看官们一起来学习一下吧!

将值转换成Number数值

function isNum(value) {

return typeof value === 'number' && !isNaN(value);

}

//加

function accAdd(arg1, arg2) {

var r1, r2, m, result;

try {

r1 = arg1.toString().split(".")[1].length;

} catch (e) {

r1 = 0;

}

try {

r2 = arg2.toString().split(".")[1].length;

} catch (e) {

r2 = 0;

}

m = Math.pow(10, Math.max(r1, r2));

result = (arg1 * m + arg2 * m) / m;

if (isNum(result)) {

return result;

} else {

return 0;

}

}

//减function Subtr(arg1, arg2) { var r1, r2, m, n, result; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); //动态控制精度长度 n = (r1 >= r2) ? r1 : r2; result = parseFloat(((arg1 * m - arg2 * m) / m).toFixed(n)); if (isNum(result)) { return result; } else { return 0; }}

//乘function accMul(arg1, arg2) { var m = 0, result, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length; } catch (e) { console.log(e); } try { m += s2.split(".")[1].length; } catch (e) { console.log(e); } result = Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); if (isNum(result)) { return result; } else { return 0; }}

//除function accDiv(arg1, arg2) { //如果除数是0,直接返回0 if (arg2 == '0') { return 0; } var t1 = 0, t2 = 0, r1, r2, result; try { t1 = arg1.toString().split(".")[1].length; } catch (e) { console.log(e); } try { t2 = arg2.toString().split(".")[1].length; } catch (e) { console.log(e); } r1 = Number(arg1.toString().replace(".", "")); r2 = Number(arg2.toString().replace(".", "")); //这里进行乘法运算,浮点数乘法运算也会出现精度问题,所以依赖accMul result = accMul((r1 / r2), Math.pow(10, t2 - t1)) if (isNum(result)) { return result; } else { return 0; }}

标签: #js计算和