본문 바로가기
Web(HTML5)

How to check if a variable is an integer in JavaScript?

by swconsulting 2017. 9. 10.


function isValidInteger(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}



hat 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));
}

With Bitwise operations

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/

Here's the yolpo: http://www.yolpo.com/embed.html?gist=a3c46f837ea7bbb708ae&autoplay=2

Performance

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.

source : https://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#comment20448200_14636652

'Web(HTML5)' 카테고리의 다른 글

Basic HTML Template  (0) 2017.09.23
jquery mobile popup show programmatically  (0) 2017.09.11
jquery dialog position  (0) 2017.08.30
ul 태그 안에 있는 li 지우기 ( Remove ul tag child)  (0) 2017.08.30
json jquery populate each example  (0) 2017.08.30