How to check for NaN with JavaScript?

If you explicitly convert a JavaScript variable to a number (e.g. by using the parseInt function), then you have to check if the value of the converted number is really a number. In case that it is not, it will present you NaN (Not a Number). You can check for NaN with the isFinite function.

Example:

1
2
3
4
5
6
// Check for hexadecimal value
var convertedNumber = parseInt('G', 16);
if(isFinite(convertedNumber) == false)
  alert('The value of the converted number is NaN!');
else
  alert('The number is: '+convertedNumber);

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.