admin管理员组

文章数量:1426314

I am using isNaN to evaluate input in text box my function is like this

function IsNumeric(n) {
    return !isNaN(n);
} 

it's working fine with numeric but not on negative values nor decimal values like 1.2,

but I will not accept negative or decimal values like 1.2

how can I do that?

Thanks

I am using isNaN to evaluate input in text box my function is like this

function IsNumeric(n) {
    return !isNaN(n);
} 

it's working fine with numeric but not on negative values nor decimal values like 1.2,

but I will not accept negative or decimal values like 1.2

how can I do that?

Thanks

Share Improve this question edited Feb 2, 2011 at 14:39 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Feb 2, 2011 at 14:27 airair 6,26426 gold badges95 silver badges126 bronze badges 1
  • n is any type text in text box.... – air Commented Feb 2, 2011 at 14:29
Add a ment  | 

3 Answers 3

Reset to default 3

You mean

function IsPostiveInteger(n) {
  var n = new Number(n);
  return !isNaN(n) && n===parseInt(n,10) && n>0;
} 

Try to use Number(n). This will return NAN if its not a number. Else will return the same number irrespective of negative or positive

Shorter Alternate solution:

function IsNumeric(n){
    // any valid number
    //return /^-?\d+(?:\.\d+)?$/.test(n);

    // only positive numbers
    //return /^\d+(?:\.\d+)?$/.test(n);

    // only positive whole numbers
    return /^\d+$/.test(n);
}

本文标签: javascriptusing isNaN to evaluate inputStack Overflow