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?
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?
4 Answers
Reset to default 4!parseFloat(num)
is false
so you are paring false >= 0
You could do this:
if(! (parseFloat(num)>=0))
But it would be more readable to do this:
if(parseFloat(num) < 0)
parseFloat
returns either a float or NaN
, but you are applying the Boolean NOT operator !
to it and then paring it to another floating point.
You probably want something more like:
var num = "10.0";
var notANumber = isNaN(parseFloat(num));
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/en/JavaScript/Reference/Operators/Operator_Precedence
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);
}
}
ref