Check whether a value is a number in JavaScript or jQuery

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHussyView Question on Stackoverflow
Solution 1 - JavascriptzadView Answer on Stackoverflow
Solution 2 - JavascriptcwallenpooleView Answer on Stackoverflow
Solution 3 - JavascriptBuffonView Answer on Stackoverflow