Tuesday, May 12, 2009

JavaScript "isInteger"

When searching for this I found dozens of implementations doing crazy things like parsing each character, string manipulation, etc. But if you really want to know if it's an integer, what about this?


function isInteger(val) {

   return (val == null || isNaN(val)) ? false : 
      ( ((1.0 * val) == Math.floor(val)) && (val.indexOf(".") == -1));

}