0

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

Venks
  • 386
  • 3
  • 7
  • What's wrong with your current method? – Rakshith Ravi Sep 16 '15 at 16:44
  • visit http://stackoverflow.com/questions/3214448/comparing-numbers-in-java?lq=1 – Sachin Verma Sep 17 '15 at 03:59
  • @RakshithRavi What's wrong with it is that it doesn't compile. – user207421 Sep 17 '15 at 04:09
  • @EJP It compiles and works fine. since Double is 8 bytes. there won't be any problem when byte, short, Integer, Long are passed. But would be a problem if BigInteger(56 bytes) is passed. Tell me an ideal way to compare two numbers or any inbuild functions that does this work – Venks Sep 17 '15 at 04:29
  • @SachinVerma : that solution only works if both are numbers are same type. If you compare 12 with 12.0 it should return true, but it returns false. Moreover I am also more curios with greater and lesser than as well not only equals. – Venks Sep 17 '15 at 04:31

1 Answers1

0

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?

user207421
  • 305,947
  • 44
  • 307
  • 483