javascript 四則運算精度修正函數(shù)代碼
更新時間:2010年05月31日 23:07:53 作者:
JS預算精度問題確實很麻煩,這個能解決一些問題,雖然有bug.
函數(shù)代碼如下:
/*
* 四則運算精度修正函數(shù)
* m 數(shù)值1(number)
* n 數(shù)值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);
}
函數(shù)用法如下:
fixMath(2.3, 1.9, '* ')
fixMath(1.98, 1.9, '- ')
fixMath(83.50, 74.15, '- ')
復制代碼 代碼如下:
/*
* 四則運算精度修正函數(shù)
* m 數(shù)值1(number)
* n 數(shù)值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);
}
函數(shù)用法如下:
復制代碼 代碼如下:
fixMath(2.3, 1.9, '* ')
fixMath(1.98, 1.9, '- ')
fixMath(83.50, 74.15, '- ')
相關文章
javascript Deferred和遞歸次數(shù)限制實例
你知道Deferred和遞歸次數(shù)限制嗎?如果還不知道,可以看看下面的實例,很好,適合新手朋友們2014-10-10JS組件Bootstrap實現(xiàn)彈出框和提示框效果代碼
這篇文章主要介紹了JS組件Bootstrap實現(xiàn)彈出框和提示框效果代碼,對彈出框和提示框感興趣的小伙伴們可以參考一下2015-12-12創(chuàng)建一個復制UBB軟件信息的鏈接或按鈕的js代碼
2008-01-01