How do you set a double value to a "non-value"

54,053

Two obvious options:

  • Use Double instead of double. You can then use null, but you've changed the memory patterns involved substantially.
  • Use a "not a number" (NaN) value:

    double d = 5.5;
    System.out.println(Double.isNaN(d)); // false
    d = Double.NaN;
    System.out.println(Double.isNaN(d)); // true
    

    Note that some other operations on "normal" numbers could give you NaN values as well though (0 divided by 0 for example).

Share:
54,053

Related videos on Youtube

Ankur
Author by

Ankur

A junior BA have some experience in the financial services industry. I do programming for my own personal projects hence the questions might sound trivial.

Updated on July 09, 2022

Comments

  • Ankur
    Ankur almost 2 years

    I have two double data elements in an object.

    Sometimes they are set with a proper value and sometimes not. When the form field from which they values are received is not filled I want to set them to some value that tells me, during the rest of the code that the form fields were left empty.

    I can't set the values to null as that gives an error, is there some way I can make them 'Undefined'.

    PS. Not only am I not sure that this is possible, it might not also make sense. But if there is some best practice for such a situation I would be keen to hear it.

  • Ankur
    Ankur almost 14 years
    Thanks ... NaN will solve my purposes. I won't be doing any arithmetic on these numbers so that will do it just nicely.
  • Jesper
    Jesper almost 14 years
    Beware with NaN that using == with them always returns false, even Double.NaN == Double.NaN is false. You must use Double.isNaN(...) to check if a double is not-a-number.
  • sleske
    sleske almost 14 years
    I also commonly use the "Double=null" trick. I'd prefer it to the NaN option, both because NaN might occur as a value, and because "null for unset" is a common practice in Java.
  • Jon Skeet
    Jon Skeet almost 14 years
    @sleske: Yes - it depends on the situation though. It could be expensive in terms of heap usage if you ended up creating huge numbers of Double objects.
  • sleske
    sleske almost 14 years
    True. But I'd usually file that under "premature optimization" and worry about it later ;-). Still, good to consider the possibility.

Related