Skip to content

Expression language not compare BigDecimals with integers [SPR-8716] #13358

@spring-projects-issues

Description

@spring-projects-issues

Giovanni Dall'Oglio Risso opened SPR-8716 and commented

The number comparison can be more accurate with BigDecimals (possibly also BigIntegers) and other number types:

This test fail, becouse the BigDecimal is converted to Integer, truncating the value to zero:

    @Test
    public void testGT() throws Exception
    {

        ExpressionParser ep = new SpelExpressionParser();
        Expression expression = ep.parseExpression("new java.math.BigDecimal('0.1') > 0");
        Boolean value = expression.getValue(Boolean.class);

        Assert.assertTrue(value);
    }

The responsible is the class org.springframework.expression.spel.ast.OpGT (but all the similar classes has the same imprinting)

@Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
     Object left = getLeftOperand().getValueInternal(state).getValue();
     Object right = getRightOperand().getValueInternal(state).getValue();
     if (left instanceof Number && right instanceof Number) {
          Number leftNumber = (Number) left;
          Number rightNumber = (Number) right;
          if (leftNumber instanceof Double || rightNumber instanceof Double) {
               return BooleanTypedValue.forValue(leftNumber.doubleValue() > rightNumber.doubleValue());
          } else if (leftNumber instanceof Long || rightNumber instanceof Long) {
               return BooleanTypedValue.forValue(leftNumber.longValue() > rightNumber.longValue());
          } else {
               return BooleanTypedValue.forValue(leftNumber.intValue() > rightNumber.intValue());
          }
     }
     return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) > 0);
}

In order you:

  • check if is a Double
  • check if is a Long
  • treat it as an Integer

I attach my modest suggestion


Affects: 3.0.5

Attachments:

Issue Links:

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)status: duplicateA duplicate of another issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions