js计算精度解决办法,这个问题一般出在计算产品数量和价格的和,如果是integer类型那么就会出现小数位不在计算内!所以要改成float类型 提供一个js类
// JavaScript Document
function arithmetic(a, sign, b){ if(isNaN(a) || isNaN(b)) return ; if (a == null || a == '') a = 0; if (b == null || b == '') b = 0; if(a.toString().indexOf(".") < 0 && b.toString().indexOf(".") < 0) return eval(a + sign + b); var ra = a.toString().replace(' ', ''); var rb = b.toString().replace(' ', ''); var arr_a = ra.split("."); var arr_b = rb.split("."); var digit_a = (arr_a.length > 1) ? arr_a[1].length : 0; var digit_b = (arr_b.length > 1) ? arr_b[1].length : 0; var size = (digit_a > digit_b ? digit_a : digit_b); var tmp_a = ra.replace('.', ''); var tmp_b = rb.replace('.', ''); var int_a; var int_b; if(size == digit_a) { int_a = Number(tmp_a); }else{ for(var i = 0; i < (size - digit_a); i++) { tmp_a += '0'; } int_a = Number(tmp_a); } if(size == digit_b) { int_b = Number(tmp_b); }else{ for(var i = 0; i < (size - digit_b); i++) { tmp_b += '0'; } int_b = Number(tmp_b); } var mul; switch(sign){ case "+": mul = size; break; case "-": mul = size; break; case "*": mul = 2 * size; break; } if (sign == '/'){ var int_result = eval(int_a + sign + int_b); }else{ var int_result = eval(int_a + sign + int_b) / Math.pow(10, mul); } return (int_result); } var result = arithmetic(10,'/',2);//计算10除以2 注意一点就是获取值的时候用不着parseFloat不要用parseInt.
roFixed(x)是定小数点后位数的方法,一定程度上是有作用的,建议加上