Home > database >  How to resolve Java.lang.numberformatexception: empty string
How to resolve Java.lang.numberformatexception: empty string

Time:01-13

I have a utility function which convert parseDouble value to string.

public static BigDecimal setValue(Object o) {
  BigDecimal value = new BigDecimal(0);
  if(o!= Null){
    value=BigDecimal.valueOf(Double.parseDouble(o.toString()));
  }
  return value;
}

I have tried with (o!=null && !isEmpty(o)) and (o!="" && o!=null) but it is still throwing same error.

Transaction amount which is processing this utility function contains empty value.

CodePudding user response:

Firstly I don't understand why you are taking object type as an input, however to resolve your issue you can do something like this. But I would strongly advice you to change the method signature it is misleading.

public static BigDecimal setValue(Object o) {
    var value = new BigDecimal(0);
    if (o != null) {
        if(o instanceof String) {
            if (((String) o).trim().length()>0) {
                value = new BigDecimal((String) o);
            }
        }
    }
    return value;
}

CodePudding user response:

I would change the method signature to BigDecimal setValue(String s). Your null check and length check code should then work fine. Also the method name is misleading. The method does not set anything. Something like convertToBigDecimal would be clearer.

  •  Tags:  
  • Related