How to Check for Integers in JavaScript

How to Check for Integers in JavaScript thumbnail
Integers are sometimes called whole numbers.

It's important to make sure the input you receive from a user on a webpage is what you expect it to be, in order to prevent errors. For example, you may be programming an online calculator that requires integers to be input. In that case, you have to make sure the user didn't input words or numbers with decimals. You can make sure the input is an integer with only a few lines of JavaScript.

Instructions

    • 1

      Create a function called "IsInteger" that takes a single argument. It will return true if the argument is an integer, and false otherwise.
      function IsInteger(x) {

      }

    • 2

      Assign a temporary variable the value of "parseInt(x)," where x is the variable we're making sure is an integer. Your code should look like:
      Function IsInteger(x) {
      var temp = parseInt(x);
      }

    • 3

      Compare the temp variable to the original. If they match, then it's an integer. Your code should now read:
      function IsInteger(x) {
      var temp = parseInt(x);
      If (temp == x) {
      return true;
      }
      return false;
      }

Tips & Warnings

  • You can check for decimal values by using the parseFloat function instead of parseInt.

Related Searches:

References

  • Photo Credit the number image by Agur from Fotolia.com

Comments

You May Also Like

Related Ads

Featured