javascript 四则运算精度修正函数代码

JS预算精度问题确实很麻烦,这个能解决一些问题,虽然有bug.

函数代码如下:

复制代码 代码如下:


/*
* 四则运算精度修正函数
* m 数值1(number)
* n 数值2(number)
* op 操作符(string)
*/
function fixMath(m, n, op) {
var a = (m+ " ");
var b = (n+ " ");
var x = 1;
var y = 1;
var c = 1;
if(a.indexOf( ". ")> 0) {
x = Math.pow(10, a.length - a.indexOf( ". ") - 1);
}
if(b.indexOf( ". ")> 0) {
y = Math.pow(10, b.length - b.indexOf( ". ") - 1);
}
switch(op)
{
case '+ ':
case '- ':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
break;
case '* ':
c = x*y
m = Math.round(m*x);
n = Math.round(n*y);
break;
case '/ ':
c = Math.max(x,y);
m = Math.round(m*c);
n = Math.round(n*c);
c = 1;
break;
}
return eval( "( "+m+op+n+ ")/ "+c);
}



  函数用法如下:

复制代码 代码如下:


fixMath(2.3, 1.9, '* ')
fixMath(1.98, 1.9, '- ')
fixMath(83.50, 74.15, '- ')

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdxxss.html