javascript 四則運(yùn)算精度修正函數(shù)代碼
更新時(shí)間:2010年05月31日 23:07:53 作者:
JS預(yù)算精度問題確實(shí)很麻煩,這個(gè)能解決一些問題,雖然有bug.
函數(shù)代碼如下:
/*
* 四則運(yùn)算精度修正函數(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, '- ')
復(fù)制代碼 代碼如下:
/*
* 四則運(yùn)算精度修正函數(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ù)用法如下:
復(fù)制代碼 代碼如下:
fixMath(2.3, 1.9, '* ')
fixMath(1.98, 1.9, '- ')
fixMath(83.50, 74.15, '- ')
相關(guān)文章
JS?中的類Public,Private?和?Protected詳解
這篇文章主要介紹了JS中的類Public,Private和Protected詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
js獲取數(shù)組任意個(gè)不重復(fù)的隨機(jī)數(shù)組元素
新建一個(gè)數(shù)組,將傳入的數(shù)組復(fù)制過來,用于運(yùn)算,而不要直接操作傳入的數(shù)組2010-03-03
提高團(tuán)隊(duì)代碼質(zhì)量利器ESLint及Prettier詳解
這篇文章主要為大家介紹了提高團(tuán)隊(duì)代碼質(zhì)量利器ESLint及Prettier使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
不同js異步函數(shù)同步的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄煌琷s異步函數(shù)同步的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05
TypeScript實(shí)現(xiàn)數(shù)組和樹的相互轉(zhuǎn)換
樹或者圖是個(gè)比較抽象的概念,并不存在這樣的數(shù)據(jù)類型。數(shù)組就比較簡(jiǎn)單了,因此數(shù)組和樹的轉(zhuǎn)換可以理解為數(shù)組和對(duì)象之間的轉(zhuǎn)換。本文將用TypeScript實(shí)現(xiàn)數(shù)組和樹的相互轉(zhuǎn)換,感興趣的可以了解一下2022-06-06
js 提取某()特殊字符串長(zhǎng)度的實(shí)例
下面小編就為大家分享一篇js 提取某()特殊字符串長(zhǎng)度的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
JavaScript導(dǎo)航腳本判斷當(dāng)前導(dǎo)航
這篇文章主要介紹了JavaScript導(dǎo)航腳本判斷當(dāng)前導(dǎo)航的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07

