51,408
社区成员
发帖
与我相关
我的任务
分享
package com.houlling.kftc.GeneralUtils;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import java.util.HashMap;
import java.util.Map;
/**
* 公式计算
*/
public class CaculationUtils {
public static Object caculation(String jexlExp, Map<String, Object> map){
JexlEngine jexl = new JexlEngine();
Expression expression = jexl.createExpression(jexlExp);
JexlContext jc = new MapContext();
for (String key : map.keySet()) {
jc.set(key, map.get(key));
}
if (null == expression.evaluate(jc)) {
return "";
}
Object o = expression.evaluate(jc);
return expression.evaluate(jc);
}
/**
* 调用方式
*/
public static void test(){
// 执行字符串表达式:(k-(x-y)*0.1),进行计算
Map<String, Object> map = new HashMap<String, Object>();
map.put("x", 1.002);
map.put("y", 1.005);
String formula = "(x+y)/2";
Object result = caculation(formula,map);
System.out.println(result);
}
}

结果居然是:1.00349999.....,求解,谢谢