搭配方程式解析函式庫: https://github.com/kgram/equation-parser
範例程式碼
<script src="./node_modules/decimal.js/decimal.js"></script>
<script type="module">
import { parse } from './node_modules/equation-parser/dist/index.esm.js';
function cal(equationString) {
function calNode(equationNode) {
switch(equationNode.type) {
case 'number':
return new Decimal(equationNode.value);
case 'plus':
return calNode(equationNode.a).plus(calNode(equationNode.b));
case 'minus':
return calNode(equationNode.a).minus(calNode(equationNode.b));
case 'multiply-dot':
return calNode(equationNode.a).mul(calNode(equationNode.b));
case 'divide-fraction':
return calNode(equationNode.a).div(calNode(equationNode.b));
default:
throw 'Unknow operator';
}
}
let equationNode = parse(equationString);
return calNode(equationNode).toString();
}
Decimal.set({ precision: 5, rounding: 4 });
// 之後計算東西就呼叫 cal 即可,算式用字串傳入
console.log(cal('1-2+3*4.3/4.1'));
</script>