SpringEL计算 Integer相除为0
使用SpringEL进行计算的时候,数据类型是Integer,进行相除的时候,得到的结果是0,该如何处理呢?
处理思路:
1,在公式里面,被除数乘以1.00
2,对数据类型进行判断,对于Integer进行转换。
直接上代码:
代码:
直接相除:
private static final ExpressionParser PARSER = new SpelExpressionParser();
public static void main(String[] args) {
testInteger();
}
public static void testInteger() {
String numStr = "3";
Integer count = 6;
Integer total = 2;
Number num1 = NumberUtils.createNumber(numStr);
StandardEvaluationContext context = new StandardEvaluationContext();
// 在StandardEvaluationContext这个上下文环境中定义一个新的变量newName,并给他赋值Mike Tesla
context.setVariable("num1", num1);
context.setVariable("count", count);
context.setVariable("total", total);
Object one = PARSER.parseExpression("#count>0?(#num1 / #count):0").getValue(context, Object.class);
System.out.println("express1: " + one);
Object two = PARSER.parseExpression("#total>0?(#num1 / #total):0").getValue(context, Object.class);
System.out.println("express2: " + two);
}
结果:
express1: 0
express2: 1
被除数乘以1.00:
Object three = PARSER.parseExpression("#count>0?(#num1 * 1.00 / #count):0").getValue(context, Object.class);
System.out.println("express3: " + three);
结果: express3: 0.5
类型转换
Object intergerStr = 3;
if(intergerStr instanceof Integer){
intergerStr = Double.parseDouble(intergerStr.toString());
}
context.setVariable("num2", intergerStr);
Object four = PARSER.parseExpression("#count>0?(#num2 / #count):0").getValue(context, Object.class);
System.out.println("express4: " + four);
结果: express4: 0.5
总结:
在SpringEL的应用中,Interger数据相除的时候,容易出现0的情况,可以从公式那边入手,被除数乘以1.00,或是对数据进行转换,对于Interger转换为Double类型。如果是大量配置的,使用后者,减少工作量。