How do I check if a variable is an integer in JavaScript, and throw an alert if it isn't? I tried this, but it doesn't work:
<html> <head> <script type="text/javascript"> var data = 22; alert(NaN(data)); </script> </head> </html>
To check if a variable is an integer in JavaScript, use Number. isInteger() . Number. isInteger() returns true or false depending on the parameter provided.
To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.
Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.
That depends, do you also want to cast strings as potential integers as well?
This will do:
function isInt(value) { return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10)); }
Simple parse and check
function isInt(value) { var x = parseFloat(value); return !isNaN(value) && (x | 0) === x; }
Short-circuiting, and saving a parse operation:
function isInt(value) { if (isNaN(value)) { return false; } var x = parseFloat(value); return (x | 0) === x; }
Or perhaps both in one shot:
function isInt(value) { return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value)) }
Tests:
isInt(42) // true isInt("42") // true isInt(4e2) // true isInt("4e2") // true isInt(" 1 ") // true isInt("") // false isInt(" ") // false isInt(42.1) // false isInt("1a") // false isInt("4e2a") // false isInt(null) // false isInt(undefined) // false isInt(NaN) // false
Here's the fiddle: http://jsfiddle.net/opfyrqwp/28/
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
// Short-circuiting, and saving a parse operation function isInt(value) { var x; if (isNaN(value)) { return false; } x = parseFloat(value); return (x | 0) === x; }
Here is a benchmark: http://jsben.ch/#/htLVw
If you fancy a shorter, obtuse form of short circuiting:
function isInt(value) { var x; return isNaN(value) ? !1 : (x = parseFloat(value), (0 | x) === x); }
Of course, I'd suggest letting the minifier take care of that.
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10)) alert("data is integer") else alert("data is not an integer")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With