Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 405
Ankur Avatar asked Jun 01 '10 09:06

Ankur


People also ask

Can a double value be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

How do you know if a double is not zero?

if(value != 0) //divide by value is safe when value is not exactly zero. Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.


Video Answer


1 Answers

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

like image 92
Jon Skeet Avatar answered Nov 07 '22 15:11

Jon Skeet