public class JexlEngineUtils { public static BigDecimal evaluateExpression ( Mapmap, String[] elementArr, String expression, int margin ){ JexlEngine jexl = new JexlEngine (); JexlContext jexlContext = new MapContext ();
//需要set源代码Math,否则报错 jexlContext.set("Math", Math.class);
//需要set源代码 BigDecimal,否则报错
jexlContext.set("BigDecimal",BigDecimal.class); for (String key : elementArr) { Object p = map.get ( key ); Double val = 0.0; if (null != p) { if (p instanceof BigDecimal) { BigDecimal temp = (BigDecimal) p; val = temp.doubleValue (); } else { if (RegexUtils.isNumberWithDot ( p.toString () )) { val = Double.valueOf ( p.toString () ); } } } jexlContext.set ( key, val ); } Expression e = jexl.createExpression ( expression ); Object obj = e.evaluate ( jexlContext ); BigDecimal result = new BigDecimal ( null == obj ? "0" : obj.toString () ); return result.setScale ( margin, BigDecimal.ROUND_HALF_UP ); } //因为精度问题引入BigDecimal
public static void main(String[] args) { MapindividualIncomeTaxMap = new HashMap<>(16); individualIncomeTaxMap.put("cashRate",5334.4); individualIncomeTaxMap.put("yearPremium",200000); String[] te = {"cashRate","yearPremium"}; System.out.println(evaluateExpression(individualIncomeTaxMap,te,"Math.floor(BigDecimal.valueOf(cashRate).multiply(BigDecimal.valueOf(yearPremium).divide(BigDecimal.valueOf(1000))))",0)); } }