Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to check for null with parseDouble?

Tags:

java

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).

like image 485
Beetroot Avatar asked Jun 08 '11 19:06

Beetroot


1 Answers

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;
like image 108
aioobe Avatar answered Oct 07 '22 13:10

aioobe