views:

374

answers:

4

Hi,

i am looking for an easy way in javascript to check if a number has a decimal place in it (is an integer) ...

23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK

if(number is integer) {...}

thx alot.

+5  A: 

Using modulus will work:

num % 1 != 0
// 23.5 % 1 = 0.5
Andy E
possibly != 0, for negative values
Jimmy
@Jimmy: true, I didn't account for negative input :-) Updated.
Andy E
Why the downvote? Is it a bad solution or did someone else want to get their answer noticed more?
Andy E
A: 

The most common solution is to strip the integer portion of the number and compare it to zero like so:

function Test()
{
     var startVal = 123.456
     alert( (startVal - Math.floor(startVal)) != 0 )
}
Thomas
Why not just `startVal != Math.floor(startVal)`?
Andy E
Nice. Same concept, but your version is even cleaner.
Thomas
A: 
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
ghostdog74
Fails for `num= 999999999999999999999`.
bobince
convert to string first and then do the re.
ghostdog74
A: 

//How about byte-ing it?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

they hardly get any exercise.

kennebec
That fails for integers larger than 2^31 - 1, because `>>` converts the value to a signed *32-bit integer*.
Matthew Crumley