Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if JavaScript value is an "integer"? [duplicate]

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.

like image 272
Kaizokupuffball Avatar asked Apr 22 '12 18:04

Kaizokupuffball


People also ask

How do you check if a value is an integer in JavaScript?

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.

How do you find if a number is a multiple of another number JavaScript?

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.


2 Answers

Try this:

if(Math.floor(id) == id && $.isNumeric(id))    alert('yes its an int!'); 

$.isNumeric(id) checks whether it's numeric or not
Math.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.

like image 149
bardiir Avatar answered Sep 20 '22 09:09

bardiir


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.

like image 24
6 revs Avatar answered Sep 17 '22 09:09

6 revs