js数字计算精度问题修正
问题描述
程序计算是一个很普遍的存在,但是语言的计算精度却是一个困扰人的问题,比说说,计算0.1+0.2,0.3+0.6,不用计算机计算,你用口算当然可以计算出分别为0.3和0.9,但是计算机计算的结果却不一样
这是加法中存在问题,乘法当中依然存在,你可以用程序计算一下4330.61*100,计算结果依然是不准确。
当着写计算结果应用到金钱的计算上的时候,就会出现大的问题,N笔交易以后产生的效果更大。所以需要一种方法来解决。至于产生的原因可以参考=>js浮点数精度问题的前世今生?
解决方法
浮点数计算本身就有精度缺失的问题,要解决他首先就不进行浮点数运算,就是将其转变为整数,然后再进行除法,换算为浮点数。
先看乘法运算
function mul(a, b) { var c = 0, d = a.toString(), e = b.toString(); try { c += d.split(".")[1].length; } catch (f) {} try { c += e.split(".")[1].length; } catch (f) {} return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c); }
首先,将两个需要运算的数字进行字符串化,然后依次判断小数点后有几位,因为后面需要进行除法,所以这里的小数点位数需要相加,然后将字符串化后的两个值去除小数点,在进行数字化,此时两个数字都已经变成了整数,此时在进行乘法运算,得出精确的结果,之后再除以因为去除小数点放大的倍数,由此得出精确地计算结果。
其他的运算就不在一一叙述了。
;(function(){ function mathService(){ this.add=function(a,b){ var c, d, e; try { c = a.toString().split(".")[1].length; } catch (f) { c = 0; } try { d = b.toString().split(".")[1].length; } catch (f) { d = 0; } return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e; } this.mul=function(a, b) { var c = 0, d = a.toString(), e = b.toString(); try { c += d.split(".")[1].length; } catch (f) {} try { c += e.split(".")[1].length; } catch (f) {} return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c); } this.sub=function(a,b){ var c, d, e; try { c = a.toString().split(".")[1].length; } catch (f) { c = 0; } try { d = b.toString().split(".")[1].length; } catch (f) { d = 0; } return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e; } this.div=function(a, b) { var c, d, e = 0, f = 0; try { e = a.toString().split(".")[1].length; } catch (g) {} try { f = b.toString().split(".")[1].length; } catch (g) {} return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e)); } } window.mathService=new mathService() })(window);