129

Possible Duplicate:
Validate numbers in JavaScript - IsNumeric()

var miscCharge = $("#miscCharge").val();

I want to check misCharge is number or not. Is there any method or easy way in jQuery or JavaScript to do this?

HTMl is

<g:textField name="miscCharge"  id ="miscCharge" value="" size="9" max="100000000000" min="0" />
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Hussy
  • 2,039
  • 4
  • 25
  • 32

3 Answers3

196
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
zad
  • 3,355
  • 2
  • 24
  • 25
  • 15
    This is even better: `return !isNaN(+n) && isFinite(n)` since for a numeric string with trailing letters the parseFloat | parseInt will return true and the second check isFInite will return false. While with unary `+` it will fail immediately. – Arman May 20 '13 at 16:29
  • 11
    "!isNaN(+n) && isFinite(n)" classifies the empty string as a number – thenickdude Aug 29 '13 at 03:03
  • 3
    I'm not sure if this is intended, but isNumber( ['5'] ) would also return true - but it's not a number, it's an array containing a number. – Katai Jun 25 '16 at 19:59
  • 1
    In one line: +str + '' === str – basil Sep 12 '18 at 11:49
34

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
6

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

Buffon
  • 159
  • 1
  • 10