如果使用了对float的计算,无论如何处理都会出现过多的小数点对计算的精准对造成影响,增加一个解决办法:
应用函数对数据进行int处理.
Code:
function reckon(str, calculate, str2) { var times, m1, m2, num, b1, b2; m1 = str.toString().split('.')[1].length; m2 = str2 == '' ? calculate.toString().split('.')[1].length: str2.toString().split('.')[1].length; times = m1 > m2 ? M1: m2; times = Math.pow(10, times); b1 = parseInt(str * times); b2 = str2 == '' ? parseInt(calculate * times) : parseInt(str2 * times); switch (calculate) { case '+': num = b1 + b2; break; case '-': num = b1 - b2; break; case '*': num = b1 * b2; break; case '/': num = b1 / b2; break; case '%': num = b1 % b2; break; default: num = b1 + b2; } return parseFloat(num / times); }
函数应用方法:
例如var a =3 + 5;var a =reckon(3,'+',5);或var a = reckon(3,5);默认为加法;
网友评论