I want to test if a number or a string is an integer or not. Even for the number like 1.00 is actually an integer.
The javascript function to test it:
function IsInt(value)
{
return (!(isNaN(value) || isNaN(parseInt(value))) && parseFloat(value) === parseInt(value));
}
In Javascript, isNaN method will return false for empty string, i.e., isNaN("") === false. However, parseInt("") will return NaN.
!(isNaN(value) || isNaN(parseInt(value)) will make sure the value is actually a number (it could be an integer or float). The next part parseFloat(value) === parseInt(value) will make sure the value is an integer type.
Here are some test results:
Take a look at this live demo on jsbin.
The javascript function to test it:
function IsInt(value)
{
return (!(isNaN(value) || isNaN(parseInt(value))) && parseFloat(value) === parseInt(value));
}
In Javascript, isNaN method will return false for empty string, i.e., isNaN("") === false. However, parseInt("") will return NaN.
!(isNaN(value) || isNaN(parseInt(value)) will make sure the value is actually a number (it could be an integer or float). The next part parseFloat(value) === parseInt(value) will make sure the value is an integer type.
Here are some test results:
IsInt("") returns false
IsInt("123abc") returns false
IsInt("abc123") returns false
IsInt("1.0") returns true
IsInt(1) returns true
IsInt(1.2) returns false
Take a look at this live demo on jsbin.
Comments