admin管理员组文章数量:1428927
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
本文标签: javascriptHow do I check if a string is NOT a floating numberStack Overflow
版权声明:本文标题:javascript - How do I check if a string is NOT a floating number? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745429878a2658279.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论