Announcement Announcement Module
Collapse
No announcement yet.
Spring Expression Language BigDecimal comparison Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Expression Language BigDecimal comparison

    Trying to compare BigDecimal numbers can provide strange results. E.g. < operator:

    Code:
    public class OpLT extends Operator {
    
    	public OpLT(int pos, SpelNodeImpl... operands) {
    		super("<", pos, operands);
    	}
    	
    	@Override
    	public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
    		Object left = getLeftOperand().getValueInternal(state).getValue();
    		Object right = getRightOperand().getValueInternal(state).getValue();
    		// TODO could leave all of these to the comparator - just seems quicker to do some here
    		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 case of two both left and right operands are of type BigDecimal, int values are compared, so expressions like "0.1<0.3" are resolved to false.

    Similar problem on the forum:

    http://forum.springsource.org/showth...-to-BigDecimal

    Is there any other solution then using some wrappers over BigDecimal (as suggested in the mentioned thread)?
Working...
X