skip to Main Content

I have a form with an input text field and I want to validate it before I submit the form.

You can enter a natural number like 1, 5, 7 etc or you can enter a float number like 1.5, 5.45, 7.38

How can I detect when the input has an Integer (natural) number or not?

If I’m using:

typeof($(input[name='myField']).val()) 

I always get it as a string.

I tried to convert the string to a number, but using parseInt or parseFloat doesn’t help, as I convert it directly from the code.

I need to know what type of number is the one in the string from the input field.

2

Answers


  1. Chosen as BEST ANSWER

    After a little more research and based on a few hints/comments on this question, i have fixed it with this simple trick (hope it will help others too).

    var myInput = $(input[name='myField']).val();
    //get the input string value and convert it to float
    var myFloatInput = parseFloat(myInput);
    
    if (myFloatInput % 1 != 0) {
    //the number is not Integer
    }else{
    //the number is Integer
    }
    

    Here are more details about this trick: Check if a number has a decimal place/is a whole number


  2.  function checkNumber(n) {
          x = `'${n}'`;
         let s = x.indexOf('.');
         if(s == '-1') {
          alert('this natural number');
         }else {
          alert('this float');
         }
      }
      checkNumber(4.5);
    

    Also you can use isInteger js function

    Number.isInteger(123);
    Number.isInteger(-123);
    Number.isInteger('123');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search