Reputation: 2146
Having some trouble trying to validate strings that are numbers in JS. isNaN in particular seems to be misbehaving.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>No Quirks!</title>
</head>
<body>
<h1>JavaScript Test</h1>
<button onclick="myNanIsTrue()">Is it a number?</button>
<p id="writeToHTML"></p>
<script type="text/javascript">
function myNanIsTrue() {
var g = parseInt("40000000") + "<br />";
var n = g;
if (isNaN(g)){
g="moo!";
}
n += g + "<br />";
document.getElementById("writeToHTML").innerHTML = n;
}
</script>
</body>
</html>
Tried a couple of permutations of this but it just doesn't seem to be working. Can anyone see why this isn't working?
Upvotes: 0
Views: 2182
Reputation: 647
isNaN means is Not a Number. This means that it is a function to check if your variable is not a number.
In your case you are concatenating <br>
to your integer, this converts your integer to a String.
/**
* Created by jjansen on 10-Mar-15 4:38 PM.
* stackoverflow
*/
var noNumber = parseInt("40000") + "<br>"; //this is now a String
var test = isNaN( noNumber ); //returns true
console.log("noNumber isNaN: " + test);
var number = parseInt("40000"); //this is a integer
test = isNaN( number );
console.log("number isNaN: " + test);
Upvotes: 1
Reputation: 5908
In your code, the value of g
will always be a string due to the way you build it.
Whenever you add up a String
and a Number
, you will get a new String
by concatenating the two values.
Therefore, in your code, isNaN(g)
will always return true
.
Upvotes: 0
Reputation: 1413
You've written:
var g = parseInt("40000000") + "<br />";
Therefore g
is a string: '40000000<br />'
.
parseInt("40000000")
returns an integer, but then you append a string to it. Javascript implicitly converts the numer to a string, then concatenates them.
String's not a number, so isNaN
(correctly) returns true
.
Upvotes: 3
Reputation: 4061
Because g
is a string (you're concatenating a string, so it will be converted to one).
Upvotes: 0