8

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

aioobe
  • 413,195
  • 112
  • 811
  • 826
Beetroot
  • 81
  • 1
  • 1
  • 2
  • If some operation on an object throws a `NullPointerException`, what more do you expect to do than checking the object for null? – asgs Jun 08 '11 at 20:02
  • The computational time to check for `null` must be thousands of time shorter than the parsing part. – toto2 Jun 08 '11 at 20:20

8 Answers8

12

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;
aioobe
  • 413,195
  • 112
  • 811
  • 826
1
  • Create a wrapper class for the amount that handles this test in the constructor/factory or handles a null amount as a special case, eg the Null option pattern
  • Use a Java utility library like guava that implements a Optional (expected to come in Guava r10)
  • Google Guava has a T firstNonNull(T first,T second) that can be used as Double.parseDouble( Objects.firstNonNull(amountStr,"0") )

  • (Switch to Scala and use the Option Pattern)

oluies
  • 17,694
  • 14
  • 74
  • 117
0

Might be a couple of years late to answer this question. The NumberUtils Class in org.apache.commons.lang3.math package has a method createDouble that does what you are asking for(https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#createDouble-java.lang.String-)

0

I was initializing an object and needed to convert from String to Double and ran in to null values from String.

A a = new A(value1, value2 == null ? null : Double.parseDouble(value2), value3....);

Smart Coder
  • 1,435
  • 19
  • 19
0

Why not initialize it beforehand to a "default" value?

String amountStr = /* some default value */

Then, when you use the variable, check for that special case.

if (amountDbl != /* some default value */)
    //parse it
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • I'm wondering what to use in place of `default` to make typing `amountStr != default` appear more elegant than `amountStr != null`. It certainly doesn't change the structure of the code at all. – Atreys Jun 08 '11 at 20:16
0

You could always surround it with try/catch or use a ternary operator (as aioobe did)

try{
   this.amountDbl = Double.parseDouble(amountStr);
} catch (Exception ex){
ex.printStackTrace();
}
Ryan Amos
  • 5,422
  • 4
  • 36
  • 56
  • ah, catching runtime exceptions especially NPE doesn't sound really good, does it? – asgs Jun 08 '11 at 20:04
  • If the try-block contains one single call to a static method I think it is fine to catch NPEs. – aioobe Jun 08 '11 at 20:10
  • Well, you can always narrow it down to just catch(NullPointerException npe) {...} catch (NumberFormatException nfe) {...} – Ryan Amos Jun 08 '11 at 20:10
0

It's not much better but you could do:

this.amountDbl = Double.parseDouble(amountStr==null ? "" : amountString);
mamboking
  • 4,559
  • 23
  • 27
  • Bad idea since `Double.parseDouble("")` throws a NumberFormatException. – aioobe Jun 08 '11 at 20:07
  • Well, I assumed that this code would already be wrapped in a try..catch anyway. You need to handle NumberFormatException in case amountStr doesn't have a valid number in it. – mamboking Jun 08 '11 at 20:10
  • 1
    `Double.parseDouble(amountStr==null ? "0.0" : amountString);` might be a better idea. – Bala R Jun 08 '11 at 20:12
  • I guess it depends on how you want to handle invalid doubles. Do you want to default to some number or do you want to bail out or maybe log, skip, and continue. There are a lot of possibilities. – mamboking Jun 08 '11 at 20:14
-1

I use this:

Double.parseDouble(str.isEmpty()?"0":str);

or

Double.parseDouble((str==null||str.isEmpty())?"0":str);

  • You should really not recommend this, it is not readable and it does an unnecessary parse-call in the case of 0. This way it is not a good piece of code – LionC Apr 23 '14 at 14:04