How to Determine if a Number Fits Into an Int in JavaScript

It is necessary at times to check whether a user-submitted value is in fact an integer. For instance, you might ask a user his age and then need to confirm that he submitted a legitimate value. This can be accomplished in JavaScript through a custom function that accepts the said value and then processes it through an "if" construct to determine whether it is an integer.

Instructions

    • 1

      Create a function that accepts a submitted value into a new variable:

      function integer_test(StrVariable)

      {

      }

    • 2

      Compare the "parseInt" and "parseFloat" values of the variable to ensure they are equal. "ParseInt" will only pull the integer values from the string. Meanwhile, "parseFloat" will pull the entire number from the string, even if it includes a decimal place. Both must be equal for the variable to be an integer:

      If((parseInt(StrVariable) == parseFloat(StrVariable))

      Insert the "if" construct between the brackets of the "integer_test" function.

    • 3

      Designate the function as true if it passes the previous "if" construct and false if it does not:

      {
      return true;
      }
      else
      {
      return false;
      }

    • 4

      Close the function with a final bracket. The function should look like this:

      function integer_test(StrVariable)

      {
      If((parseInt(StrVariable) == parseFloat(StrVariable))
      {
      return true;
      }
      else
      {
      return false;
      }
      }

    • 5

      Call the function by designating it to a variable:

      var IsInteger = integer_test(StrVariable)

      Replace "StrVariable" with the variable you need to inspect.

Related Searches:

References

Comments

Related Ads

Featured