Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  107] [ 6]  / answers: 1 / hits: 18293  / 15 Years ago, mon, august 24, 2009, 12:00:00

How can I test a variable to ascertain if it contains a number, and it is an integer?



e.g.



if (1.589 == integer) // false
if (2 == integer) // true


Any clues?


More From » numbers

 Answers
2
num % 1 === 0


This will convert num to type Number first, so any value which can be converted to an integer will pass the test (e.g. '42', true).



If you want to exclude these, additionally check for



typeof num === 'number'


You could also use parseInt() to do this, ie



parseInt(num) == num


for an untyped check and



parseInt(num) === num


for a typed check.



Note that the tests are not equivalent: Checking via parseInt() will first convert to String, so eg true won't pass the check.



Also note that the untyped check via parseInt() will handle hexadecimal strings correctly, but will fail for octals (ie numeric strings with leading zero) as these are recognized by parseInt() but not by Number(). If you need to handle decimal strings with leading zeros, you'll have to specify the radix argument.


[#98841] Thursday, August 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;