Comparing the values of two generic Numbers

后端 未结 12 1760
小鲜肉
小鲜肉 2020-11-27 04:48

I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I

12条回答
  •  时光取名叫无心
    2020-11-27 05:23

    if(yourNumber instanceof Double) {
        boolean greaterThanOtherNumber = yourNumber.doubleValue() > otherNumber.doubleValue();
        // [...]
    }
    

    Note: The instanceof check isn't necessarily needed - depends on how exactly you want to compare them. You could of course simply always use .doubleValue(), as every Number should provide the methods listed here.

    Edit: As stated in the comments, you will (always) have to check for BigDecimal and friends. But they provide a .compareTo() method:

    if(yourNumber instanceof BigDecimal && otherNumber instanceof BigDecimal) { 
        boolean greaterThanOtherNumber = ((BigDecimal)yourNumber).compareTo((BigDecimal)otherNumber) > 0;
    } 
    

提交回复
热议问题