0

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.

borchvm
  • 3,533
  • 16
  • 44
  • 45
Clau
  • 1
  • 1

2 Answers2

0

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

Clau
  • 1
  • 1
-1
 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');
  • I need to see if it is an Integer (natural number) or a Float, based on the string input. – Clau Mar 31 '23 at 07:39