128

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" />
1

3 Answers 3

196
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
"!isNaN(+n) && isFinite(n)" classifies the empty string as a number
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.
In one line: +str + '' === str
35

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).

3 Comments

vote down because Your regex does not work if val is -1 or 1.5
Worth noting that evaluation of an empty string is not what you'd expect: isNaN('') == false and isFinite('') == true
@transang Indeed, otherwise using regex is probably the only reliable way if you want to test integers
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

2 Comments

isNaN(null) returns false, isNaN("") returns false
isNaN(true) and isNaN(false) also return false

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.