Possible Duplicate:
Check if a variable contains a numerical value in Javascript?
How do I check if variable is an integer in jQuery?
Example:
if (id == int) { // Do this }
Im using the following to get the ID from the URL.
var id = $.getURLParam("id");
But I want to check if the variable is an integer.
The Number. isInteger() method in JavaScript is used to check whether the value passed to it is an integer or not. It returns true if the passed value is an integer, otherwise, it returns false.
To check if one number is a multiple of another number, use the modulo operator % . The operator returns the remainder when one number is divided by another number. The remainder will only be zero if the first number is a multiple of the second.
Try this:
if(Math.floor(id) == id && $.isNumeric(id)) alert('yes its an int!');
$.isNumeric(id)
checks whether it's numeric or notMath.floor(id) == id
will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.
Here's a polyfill for the Number
predicate functions:
"use strict"; Number.isNaN = Number.isNaN || n => n !== n; // only NaN Number.isNumeric = Number.isNumeric || n => n === +n; // all numbers excluding NaN Number.isFinite = Number.isFinite || n => n === +n // all numbers excluding NaN && n >= Number.MIN_VALUE // and -Infinity && n <= Number.MAX_VALUE; // and +Infinity Number.isInteger = Number.isInteger || n => n === +n // all numbers excluding NaN && n >= Number.MIN_VALUE // and -Infinity && n <= Number.MAX_VALUE // and +Infinity && !(n % 1); // and non-whole numbers Number.isSafeInteger = Number.isSafeInteger || n => n === +n // all numbers excluding NaN && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers && !(n % 1); // and non-whole numbers
All major browsers support these functions, except isNumeric
, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:
"use strict"; Number.isNumeric = Number.isNumeric || n => n === +n; // all numbers excluding NaN
Alternatively, just inline the expression n === +n
manually.
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