user244394
user244394

Reputation: 13448

How to do comparison correctly

I am trying to check that min is always less then max and min and max value is always a number and min and max is not empty.

I noticed that it never checks for that but goes straight to error msg. What am i doing wrong?

var min=30
var max=5000;
if(isNaN(min)=="false" || isNaN(max)=="false") && (min!=""|| max!="") && (max > min))
{
 document.write(min+ max);
}else
{
 document.write("give error msg");
}

Upvotes: 0

Views: 55

Answers (2)

somethinghere
somethinghere

Reputation: 17340

You should use JavaScript Number()to check if something is a Number. NaN evaluates to false anyhow, so you only have to check if this satisfies ALL your requirements, not some. If min is not a number, fail, if max is not a number, fail, if min is smaller than max, fail. This looks like this:

var min = 30
var max = 5000;

// You only need to check if its a Number using the default Number function which will
// return NaN if its not and convert if it can be converted.
if(Number(min) && Number(max) && (min <= max)){
    document.write(min + ", " + max);
} else {
    document.write("Min or Max is not a number or Min is bigger than Max");
}

Now, as some have pointed out, this will have some edge cases, so heres something that gets around it:

function getNumber(n){
    // Take a number 'n' and return 0 if false if its not a number.
    return Number(n) === 0 ? 0 : Number(n) || false;
    // Broken down this means:
    // Check if n is the number 0. Yes? Return 0. No? Check if n is a number. Yes? Return that. No? Return false;
}
if(getNumber(min) !== false && getNumber(max) !== false && (min <= max)){
    document.write(min + ", " + max);
}

Or as @IsmaelMigual said in the comments, make it simpler by dividing by 1 and then comparing:

function isNumber(n){
    // Returns true or false
    return n / 1 == n / 1;
}
if(isNumber(min) && isNumber(max) && (min <= max)){
    document.write(min + ", " + max);
}

Upvotes: 4

Burki
Burki

Reputation: 1216

if(isNaN(min)=="false" will always return false, because the function will either return true or false, but never "false" (which is a string).
Also, you should have use "and" in the first brackets.
Try this instead:
if(! isNaN(min) && ! isNaN(max)) && (...)
Edit: try this condition:
if((! isNaN(min) && ! isNaN(max)) && max> min && min > 0 ) { (...)

Upvotes: 0

Related Questions