## Friday, 8 April 2011

### Double.NaN Definition

The Double class defines a little understood value of NaN - or ‘Not A Number’. This sounds pretty simple at first glance, after-all an alphanumeric String is not a number - isn’t it?

It turns out that you’ll never know as Double.valueOf(...) or Double.parseDouble(...) will throw a NumberFormatException exception if you try to do something like:

`Double.valueOf("test");`

…so although the string “test” is not a number, it’ll never be Double.NaN.

Double.NaN is in fact defining a few very specific mathematical cases, with the most obvious one being the divisions 0/0 and ±∞/±∞ For a complete list take a look at wikipedia.

```  /** Definition of Not a Number */   public static final double NAN = 0.0d / 0.0;   public static void main(String[] args) {     // This will print false     boolean test = Double.isNaN(2.2);     System.out.println("isNaN Test Result: " + test);     // This will print true     test = Double.isNaN(NAN);     System.out.println("isNaN Test Result: " + test);     // A Double.NaN + a double remains as Double.NaN     Double d = Double.NaN + 1.0;     System.out.println(d);     // This will throw a NumberFormatException     Double invalid = Double.valueOf("test");     System.out.println("This is invalid: " + invalid);   }```