48

Possible Duplicate:
Comparing NaN values for equality in Javascript

Can anyone tell me why this is not working?

if(inbperr == NaN) {
    document.getElementById('inbclo').value = "N/A";
}
else {
    document.getElementById('inbclo').value = "%" + inbperr;
}

Instead of returning a percentage value, or "N/A", I want it to return "%NaN".

Banana
  • 2,435
  • 7
  • 34
  • 60
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Just an alternative syntax which is DRY-er... `document.getElementById('inbclo').value = isNaN(inbperr)?'N/A':"%" + inbperr;` – Basic Jul 06 '12 at 00:37
  • Possible duplicate of http://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript – Foreever Jul 14 '14 at 04:20
  • 2
    `function isReallyNaN(a) { return isNaN(a) && "number" == typeof a };` – SpYk3HH Jan 19 '15 at 20:51

2 Answers2

89

NaN's are unusual: they are not equal to anything, even themselves. You need to use isNaN(inbperr) to tell whether a value is a NaN or not.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 1
    For more information please read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FisNaN – dav_i Jun 10 '13 at 15:02
  • 19
    `typeof NaN` ======> `"number"` WTF? No, it's *not* a number, we established that. – charltoons Apr 19 '14 at 20:49
  • 1
    @charltoons It's defined by the floating point standard. – danijar Dec 07 '14 at 10:20
2

NaN is Not a Number. One of few JavaScript toxic types. It can reduce whole expression to NaN.

http://www.crockford.com/javascript/encyclopedia/

CoR
  • 3,826
  • 5
  • 35
  • 42
  • Why "_toxic""? :] `NaN` usually appears, when you try to divide by zero. According to math (at least this, that I've learnt years ago), result isn't a number (is an infinity or something similar strange / toxic). How would you like to represent this in Javascript? – trejder Jul 18 '13 at 07:37
  • 3
    it's "toxic" because whole calculation is reduced to NaN. Ex: a*b*c/d-e+f. If any of variables is NaN whole calcultion becomes NaN. No exception, no warning, script continues to run and carry that NaN until it hits the wall. So you can find NaN in strange places. – CoR Jul 18 '13 at 12:40
  • From this point of view -- agree! :] – trejder Jul 19 '13 at 06:35
  • 1
    @whoever gave me -1 : Explain yourself or learn this topic better. NaN is toxic :) – CoR Aug 17 '15 at 14:54
  • Hmm toxic? So all those clever people who put ears into defining the IEEE floating point standard went astray here .... me thinks not! – nyholku Feb 12 '17 at 18:09
  • NaN !== NaN // true – CoR Feb 15 '17 at 17:08