-1

I have to convert Strings to Doubles, but may be I have a null value. Does it work with Double.parseDouble(stringValue) or Double.valueOf(stringValue)?

What is the difference between this two methods?

Thank you in advance.

Naman
  • 27,789
  • 26
  • 218
  • 353
Rubén Cotera
  • 52
  • 2
  • 11
  • You're asking two different questions here. One of them is a duplicate of [What is the difference between Double.parseDouble(String) and Double.valueOf(String)?](https://stackoverflow.com/questions/10577610/what-is-the-difference-between-double-parsedoublestring-and-double-valueofstr). Please restrict yourself to one question per question. – khelwood Jan 09 '19 at 12:41

1 Answers1

3

Neither method makes any difference. Both will throw a NullPointerExecption. Instead, you need to add a helper method which returns a Double e.g.

static Double parseDouble(String s) {
    return s == null ? null : Double.parseDouble(s);
}

or you can return a double by having a default value

static double parseDouble(String s, double otherwise) {
    return s == null ? otherwise : Double.parseDouble(s);
}

a suitable value might be Double.NaN

static double parseDouble(String s) {
    return s == null ? Double.NaN : Double.parseDouble(s);
}
dur
  • 15,689
  • 25
  • 79
  • 125
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130