2

Can anyone point me to some code to determine if a number in JavaScript is even or odd?

I'm trying to do something like:

if(intellect is even)
{
    var magic1 = intellect/2;
}
else
{
    var magic1 = (intellect-1)/2
}

var magicdamage = Math.floor(Math.random) * (intellect + weaponi) + magic1
Bradley McInerney
  • 1,341
  • 4
  • 15
  • 14
  • number%2 would tell if zero then is even else is odd, this is how math works. I dont have time but I believe: first convert string to int then do the math in your if statement should work. – Michael Mao Jun 05 '13 at 01:08
  • 1
    If you typed this exact same question on google you'd get the answer faster... just saying :) – Marlon Bernardes Jun 05 '13 at 01:10

5 Answers5

21

Use the modulus operator

if(intellect % 2 == 0)
{
  alert ('is even');
}
else
{
  alert('is odd');
}
TGH
  • 38,769
  • 12
  • 102
  • 135
8

I think the most robust isEven function is:

function isEven(n) {
  return n == parseFloat(n) && !(n % 2);
}

which leads to:

function isOdd(n) {
  return n == parseFloat(n) && !!(n % 2);     
}

See Testing whether a value is odd or even

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209
2

if( var % 2 == 0){ /*even*/} else {/*odd*/}

Works for Java, Javascript and any other language. It's a very simple solution, that's why it often doesn't come into your mind until you've seen it somewhere.

The modulo operator % will return the remainder of a division. If the number being divided is even, the remainder is 0.

rath
  • 3,655
  • 1
  • 40
  • 53
2

Like this:

var i = 2;

if (i%2)
    // i is odd
else
    // i is even
francisco.preller
  • 6,559
  • 4
  • 28
  • 39
0

Try using this:

var number = 3;

if (number % 2)
{ 
   //it is odd
}
else
{
   //it is even
}
Walter Macambira
  • 2,574
  • 19
  • 28