Move from String to Double avoiding Null error and Malformato in Java

1

What is the optimal way to pass a String to Double ?

Taking into account if the string is null is equivalent to 0.0 and if there is no number to convert also 0.0

0.125   > 0.125
a3.72b  > 3,72
abcde   > 0.0
null    > 0.0

I have the following but with a bug in passing a3.72b that returns 0.0 and I would like it to return 3.72 , not if with a regular expression the whole process is more efficient

  private static Double StringToDouble(String s) {
    Double d = 0.0;

   try {
        d = (s!=null) ? Double.valueOf(s) : 0.0;

   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   }     
    return d;   

  }
    
asked by Webserveis 16.11.2017 в 20:15
source

3 answers

6

If your requirement requires only the numerical values, the decimal point and the negative sign if it exists; as an option you can add a REGEX to eliminate the non-numeric characters, keeping the negative sign if it exists:

 s = s.replaceAll("[^\d.-]", "");

method:

private static Double StringToDouble(String s) {
    Double d = 0.0;
    //Elimina valores no numericos
    s = s.replaceAll("[^\d.-]", "");
    try {
        d = (s!=null) ? Double.valueOf(s) : 0.0;

    }catch (NumberFormatException e){
        System.out.println("not a number");
    }
    return d;

}

These are examples of what the method would do:

  • Chain value "0.125" , result: 0.125
  • Chain value "a3.72b" , result: 3.72
  • Chain value "null" , result: 0.0
  • Chain value "a56hello.world98" , result: 56.98
  • Chain value "-56.98" , result: -56.98
  • Chain value "-a56hello.world98" , result: -56.98
answered by 16.11.2017 / 20:32
source
2

The most advisable, in my opinion and daily use, is that you leave it as null (null) when it is not convertible and when you always expect it to be a valid number. On the other hand, when the use of the number is required, it is best to throw the exception.

    private static Double StringToDouble(String s) {
       Double d = null;

       if(s!=null){
          try {
               d = Double.valueOf(s);
          }catch (NumberFormatException e){
               // ignora el error o sálvalo en la bitácora para referencia.
          }
       }
       return d;   
    }
    
answered by 16.11.2017 в 20:50
-2

I just found several ways

Double d= amountStr != null ? Double.parseDouble(amountStr) : 0;

Inside a function

public static double parseDoubleOrNull(String str) {
    return str != null ? Double.parseDouble(str) : 0;
}

is used

double d = parseDoubleOrNull(ammountStr);

And to check if it is null, detecting bad format

public static double parseDoubleSafely(String str) {
    double result = 0;
    try {
        result = Double.parseDouble(str);
    } catch (NullPointerException npe) {
    } catch (NumberFormatException nfe) {
    }
    return result;
}

Excerpted from this answer SO

    
answered by 21.11.2017 в 20:12