amountStr
is a value that occasionally contains a double value represented as a string.
I want to use Double.parseDouble
to read it into a double
variable: amountDbl
.
this.amountDbl = Double.parseDouble(amountStr);
It seems to throw a NullPointerException
if amountStr
doesn't have a value.
Does this mean I have to write a check like this every time?
if(amountStr!=null)
this.amountDbl = Double.parseDouble(amountStr);
Because I have so many statements like this in my code, I'm hoping for a more concise way of doing this check (or avoiding it).
You get a conciser expression if you use the ternary operator:
this.amountDbl = amountStr != null ? Double.parseDouble(amountStr) : 0;
or write your own utility function
public static double parseDoubleOrNull(String str) {
return str != null ? Double.parseDouble(str) : 0;
}
and do
this.ammountDbl = parseDoubleOrNull(ammountStr);
Note however that this doesn't protect you against malformed doubles. If this is a concern I suggest you go with the utility function and do something like this:
public static double parseDoubleSafely(String str) {
double result = 0;
try {
result = Double.parseDouble(str);
} catch (NullPointerException npe) {
} catch (NumberFormatException nfe) {
}
return result;
}
If you're after concise code you could even do
import static pkg.UtilClass.parseDoubleSafely;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With