Reputation: 5158
var num = "10.00";
if(!parseFloat(num)>=0)
{
alert("NaN");
}
else
{
alert("Number");
}
I want to check if a value is not a float number, but the above code always returns NaN
, any ideas what I am doing wrong?
Upvotes: 2
Views: 1906
Reputation: 1653
function isFloat(value) {
if(!val || (typeof val != "string" || val.constructor != String)) {
return(false);
}
var isNumber = !isNaN(new Number(val));
if(isNumber) {
if(val.indexOf('.') != -1) {
return(true);
} else {
return(false);
}
} else {
return(false);
}
}
Upvotes: 0
Reputation: 136697
parseFloat
returns either a float or NaN
, but you are applying the Boolean NOT operator !
to it and then comparing it to another floating point.
You probably want something more like:
var num = "10.0";
var notANumber = isNaN(parseFloat(num));
Upvotes: 3
Reputation: 60584
Because !
has a higher precedence than >=
, so your code does
!parseFloat(num)
which is false
Then
>= 0
, false
is coerced into 0
, and 0 >= 0
is true, thus the alert("NaN")
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
Upvotes: 1
Reputation: 944009
!parseFloat(num)
is false
so you are comparing false >= 0
You could do this:
if(! (parseFloat(num)>=0))
But it would be more readable to do this:
if(parseFloat(num) < 0)
Upvotes: 4