最近寫了一個純靜態的在線四則運算檢測,在這個過程中我發現分數的運算比較麻煩,所以就在github上找到了這個math.js庫
這個庫也是相當的強大
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/4.0.1/math.min.js"></script>
這個就是cdnjs的地址,當然也可以去github或者官網上下載
http://mathjs.org/
我閱讀的官方的文檔之后,發現解釋文檔里介紹分數運算的部分實在是太少了
而且按照文檔里的方法,我得到的運算結果是一個小數,而不是分數
所以我就簡單分析了一下運算函數的返回值
結果為一個對象
其中包括s、n、d三個屬性
s(符號)如果為1表示為正值 -1則表示為負值
n (分子)
d (分母)
我這里簡單實現了一個結果轉分數字符串
var fuhao; if(FuHao[i]==1) { fuhao = '+'; Result[i] = Number1[i]+Number2[i]; } else if(FuHao[i]==0) { fuhao = '-'; Result[i] = Number1[i]-Number2[i]; } else if(FuHao[i]==2) { fuhao = 'x'; Result[i] = Number1[i]*Number2[i]; } else { fuhao = "÷"; Result[i] = Number1[i]/Number2[i]; } text.value = text.value + Number1[i]+" "+fuhao+" "+Number2[i]+" = \n"; } for(var i=0;i<5;i++) { var fuhao; if(FuHao_FenShu[i]==1) { fuhao = '+'; var str = ""; var temp = math.add(math.fraction(Number_FenShu1[i]),math.fraction(Number_FenShu2[i])); if(temp.s == -1) { str = str+"-1"; } str = str + temp.n +"/" +temp.d; Result_FenShu[i] = str; } else if(FuHao_FenShu[i]==0) { fuhao = '-'; var str = ""; var temp = math.subtract(math.fraction(Number_FenShu1[i]),math.fraction(Number_FenShu2[i])); if(temp.s == -1) { str = str+"-1"; } str = str + temp.n +"/" +temp.d; Result_FenShu[i] = str; } else if(FuHao_FenShu[i]==2) { fuhao = 'x'; var str = ""; var temp = math.multiply(math.fraction(Number_FenShu1[i]),math.fraction(Number_FenShu2[i])); if(temp.s == -1) { str = str+"-1"; } str = str + temp.n +"/" +temp.d; Result_FenShu[i] = str; } else { fuhao = '÷'; var str = ""; var temp = math.divide(math.fraction(Number_FenShu1[i]),math.fraction(Number_FenShu2[i])); if(temp.s == -1) { str = str+"-1"; } str = str + temp.n +"/" +temp.d; Result_FenShu[i] = str; } text.value = text.value + Number_FenShu1[i]+" "+fuhao+" "+Number_FenShu2[i]+" = \n"; }