最近写了一个纯静态的在线四则运算检测,在这个过程中我发现分数的运算比较麻烦,所以就在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"; }