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.

4

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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');

1 Comment

I need to see if it is an Integer (natural number) or a Float, based on the string input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.