-3

I have a variable called -- double percentage and I wanted to print it using

System.out.format("height is %3.1f percent of the length\n",percentage);

When I don't enter a value for the height it returns this NaN percent of the length. What does System.out.format() do exactly?

And what does NaN mean and why does it get displayed in the output message?

zx485
  • 28,498
  • 28
  • 50
  • 59
Jim6834
  • 1
  • 4

1 Answers1

0

It's not what format is doing - a float or double can have a distinguishable value known as NaN, for "not a number", for a mathematically invalid result.

If you try and format such a NaN value, then format will appropriately represent it as the string "NaN.

Presumably you have some calculation resulting in a NaN value. Maybe there's an arithmetic operand that's uninitialized, though I'd have expected that to result in a "not initialized" compile-time error. Without that code, I can only guess how you're getting the NaN result.

Related SO question: what does NaN mean? - this is not really a duplicate, because of the 'format' angle in the present question.

IEEE 754 info on NaN and infinity from Wikipedia.

A simple example:

class Nan {
    public final static void main(String[] args) {
        double a = 0, b = 0;
        double c = a / b;
        System.out.format("%f / %f = %f \n", a, b, c);
    }
}

Result:

$ java Nan
0.000000 / 0.000000 = NaN