How to find that a number is float
or integer
?
1.25 --> float
1 --> integer
0 --> integer
0.25 --> float
<
It really doesn't have to be so complicated. The numeric value of an integer's parseFloat() and parseInt() equivalents will be the same. Thus you can do like so:
function isInt(value){
return (parseFloat(value) == parseInt(value)) && !isNaN(value);
}
Then
if (isInt(x)) // do work
This will also allow for string checks and thus is not strict. If want a strong type solution (aka, wont work with strings):
function is_int(value){ return !isNaN(parseInt(value * 1) }
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.
is_int() => Check if variable type is integer and if its content is integer
is_float() => Check if variable type is float and if its content is float
ctype_digit() => Check if variable type is string and if its content has only decimal digits
Update 1
Now it checks negative numbers too, thanks for @ChrisBartley comment!
This solution worked for me.
<html>
<body>
<form method="post" action="#">
<input type="text" id="number_id"/>
<input type="submit" value="send"/>
</form>
<p id="message"></p>
<script>
var flt=document.getElementById("number_id").value;
if(isNaN(flt)==false && Number.isInteger(flt)==false)
{
document.getElementById("message").innerHTML="the number_id is a float ";
}
else
{
document.getElementById("message").innerHTML="the number_id is a Integer";
}
</script>
</body>
</html>
Condtion for floating validation :
if (lnk.value == +lnk.value && lnk.value != (lnk.value | 0))
Condtion for Integer validation :
if (lnk.value == +lnk.value && lnk.value == (lnk.value | 0))
Hope this might be helpful.
How about this one?
isFloat(num) {
return typeof num === "number" && !Number.isInteger(num);
}
Any Float number with a zero decimal part (e.g. 1.0, 12.00, 0.0) are implicitly cast to Integer, so it is not possible to check if they are Float or not.