Bluemagica
Bluemagica

Reputation: 5158

How do I check if a string is NOT a floating number?

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

Answers (4)

devan
devan

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);
 }
}

ref

Upvotes: 0

Greg Beech
Greg Beech

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

Andreas Wong
Andreas Wong

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

Quentin
Quentin

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

Related Questions