简体   繁体   中英

How do I compare two `Number` s in Java?

I am writing a block of code, which has to support both Strings and Numbers because Number could be in String representation(if string convert to Number and then compare) when input Numbers (AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Rational, Short etc).

How do I compare? case 1: input - Integer, lower - Decimal, upper - BigInteger

case 2: input - Float, lower - Integer, upper - Long

public boolean isNumberRange(final Object input, final Object lower, final Object upper){
    boolean result = false;
    final Number nInput = getNumber(input);
    final Number nLower = getNumber(lower);
    final Number nUpper = getNumber(upper);

    if(nInput != null && nLower != null && nUpper != null)
    {
            Double dInput = nInput.doubleValue();
            Double dLower = nLower.doubleValue();
            Double dUpper = nUpper.doubleValue();
            if(dLower <= dInput && dInput <= dUpper && dInput >= dLower){
                result = true;
            }
    }
    return result;
}

private Number getNumber(Object object) throws NumberFormatException{
    if(object instanceof String){
        final String sObject = object.toString();
        if(NumberUtils.isNumber(sObject)) {
            return NumberUtils.createNumber(sObject);
        }
    }
    if(object instanceof Number){
        return (Number) object;

    }
    else{
        return null;
    }
}

Here in the above example I am converting number to Double and comparing. Is this the right way? Does is address BigInteger and AtomicLong,etc please let me know. Thanks

Here in the above example I am converting number to Double and comparing. Is this the right way?

No. Convert it to double .

Does is address BigInteger and AtomicLong,etc please let me know.

Please let you know what?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM