import java.text.DecimalFormat;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
public class MathEval {
public static String getValue(String str) {
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();;
Object result = cx.evaluateString(scope, str, null, 1, null);
double res = Context.toNumber(result);
DecimalFormat df = new DecimalFormat("0.00");
return String.valueOf(df.format(Math.floor(res *100+.5)/100));
} finally {
Context.exit();
}
}
public static String getValue1(String str) {
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();;
Object result = cx.evaluateString(scope, str, null, 1, null);
String res = Context.toString(result);
return res;
} finally {
Context.exit();
}
}
}
引入org.mozilla包。
用法:new MathEval().getValue("1*2+3/4") ; 支持三元运算。。
本文介绍了一个Java类MathEval,该类能够解析并计算数学表达式。通过使用org.mozilla.javascript库,MathEval实现了字符串形式的数学表达式的求值功能,并支持基本的算术运算及三元运算。代码中提供了两种方法:一种返回双精度浮点数结果,另一种返回字符串形式的结果。

753

被折叠的 条评论
为什么被折叠?



