最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I check if a string is NOT a floating number? - Stack Overflow

programmeradmin1浏览0评论
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?

Share Improve this question asked May 18, 2012 at 8:42 BluemagicaBluemagica 5,15812 gold badges49 silver badges73 bronze badges
Add a ment  | 

4 Answers 4

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

发布评论

评论列表(0)

  1. 暂无评论