Check the value of float or int in jquery

I have the following html field for which I need to check if the input value is float or int,

<p class="check_int_float" name="float_int" type="text"></p> $(document).ready(function(){ $('.check_int_float').focusout(function(){ var value = this.value if (value is float or value is int) { // do something } else { alert('Value must be float or int'); } }); }); 

So how to check if the value is float or int in jquery.

I need to find / check both cases, be it float or int, because later, if the value was float , I will use it for some purpose and similarly for int .

+4
source share
4 answers

use typeof to check type, then value % 1 === 0 to identify int as below,

 if(typeof value === 'number'){ if(value % 1 === 0){ // int } else{ // float } } else{ // not a number } 
+10
source

You can use regex

 var float= /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/; var a = $(".check_int_float").val(); if (float.test(a)) { // do something } //if it NOT valid else { alert('Value must be float or int'); } 
+1
source

You can use regex to determine if the input matches:

 // Checks that an input string is a decimal number, with an optional +/- sign character. var isDecimal_re = /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/; function isDecimal (s) { return String(s).search (isDecimal_re) != -1 } 

Keep in mind that the value from the input field is still a string, not a number .

0
source

I think the best idea would be to check this, for example, check the remainder when dividing by 1:

 function isInt(value) { return typeof value === 'Num' && parseFloat(value) == parseInt(value, 10) && !isNaN(value); } 
0
source

Source: https://habr.com/ru/post/975146/


All Articles