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") ; 支持三元运算。。