您的位置:首页 > Web前端 > JavaScript

javascript数值四则运算精度修正函数

2012-03-07 17:01 417 查看
转载自:http://topic.csdn.net/u/20070622/09/c6a389e4-0b52-49c3-9c99-49e126d78a3e.html

我对上面的代码进行了修改,现在直接使用就可以了

/*

* 四则运算精度修正函数

* m 数值1(可以是数字字符串)

* n 数值2(可以是数字字符串)

* op 操作符(string)

*/

function fixMath(m, n, op) {

var m=Number(m);

var n=Number(n);

var a=String(m);

var b=String(n);

var x=1;

var y=1;

var c=1;

if(a.indexOf( ".")> 0) {

x=Math.pow(10, a.length-a.indexOf("."));

}

if(b.indexOf( ".")> 0) {

y=Math.pow(10, b.length-b.indexOf("."));

}

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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: