SpringEL计算 Integer相除为0

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类型。如果是大量配置的,使用后者,减少工作量。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天狼1222

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值