0

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236
air
  • 6,136
  • 26
  • 93
  • 125

3 Answers3

3

You mean

function IsPostiveInteger(n) {
  var n = new Number(n);
  return !isNaN(n) && n===parseInt(n,10) && n>0;
} 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 3
    Actually the === is correct - it means that n not only has the same value but is the same type, e.g. an integer. http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – mplungjan Feb 02 '11 at 14:58
2

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

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
1

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);
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • But the asker does not want decimals nor negative values – mplungjan Feb 02 '11 at 14:42
  • @mplungjan: Yea, I was playing around with it after I saw the other's answers. Now It will only accept whole numbers. (as shown [on jsfiddle](http://www.jsfiddle.net/bradchristie/VeXQP/)) – Brad Christie Feb 02 '11 at 14:47
  • You mean as in 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 – mplungjan Feb 02 '11 at 15:00