Testing if a value is an integer in Javascript

I decided to post this article after doing a Google search for "Javascript is_int()" and "Javascript integer test" on Google.

I got plenty of results back, but each result that I looked at contained a function which don't always work as intended, either because the logic was flawed, or because it won't work with variables which are typed as a string, such as form input values.

Let me explain...

Javascript is_int() function example 1

Some sites proposed a solution which involved doing a pattern matching each for a decimal point in the variable. Something along the lines of this:

function is_int(value){
   for (i = 0 ; i < value.length ; i++) {
      if ((value.charAt(i) < '0') || (value.charAt(i) > '9')) return false 
    }
   return true;
}

Why this won't work

If I enter 1.00 or 2.00 as my variable, the function will return false, even though the number I entered is in fact an integer.

Javascript is_int() function example 2

Some solutions propose doing a parseInt() on the value, and returning false if this is NaN:

function is_int(value){
   return !isNaN(parseInt(value * 1))
}

Why this won't work

Whilst this will work with standard integers, it will also return true for floats, and it won't work with data typed as string (for example, form submission data).

Finally: a Javascript is_int() function which WORKS:

If the value of a variable is an integer, then the numeric value of it's parseFloat() and parseInt() equivalents will be the same, so:

function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else {
      return false;
  }
}

NOTE: the above function uses WEAK VARIABLE TYPING - if you need to check is_int() using strong variable typing, you will need to use a different approach.

“ From the outset, invent Partners got the balance right and were prepared to listen to our needs, whilst at the same time offering their depth of knowledge and experience. The end product we received is exceptional and has since proven its worth, fundamentally from a ‘back end’ input and management information viewpoint and importantly from a ‘front end’ consumer ease of use stance. Needless to say, we are growing our business as a result, with 80% of web business as ‘net new’. ”
Ged, Vertigrow Ltd

Contact Us

© 2019 Invent Partners Ltd | Supporters of FdA Web Design, Wakefield