Home > InDesign Scripts > QuickTip: Check if a number is even or odd

QuickTip: Check if a number is even or odd

How to check if a number is even or odd? We can use Modulus operator (%), which returns the remainder of a division operation. If you divide some number by two, a remainder of 0 indicates an even number, while a remainder of 1 indicates an odd number. Best and easiest way is to create ‘Number’ prototype.

Here is prototype:

Number.prototype.isEven = function (){
    return (this%2 == 0) ? true : false;
}

Now declare some number:

var myNum = Number(15);

And check if it’s even or odd:

alert(myNum.isEven()); // returns false

[UPDATE]
Thanks Jongware!

Also, you can do it like this:

alert(!(myNum & 1)); // returns false

That’s it!

Have fun! :D

About these ads
Categories: InDesign Scripts Tags:
  1. Jongware
    August 25, 2010 at 00:46 | #1

    It’s also possible to do

    alert (!(myNum & 1)) …

    • August 25, 2010 at 00:50 | #2

      Thanks Jongware!
      I’ll update the post ;)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 34 other followers

%d bloggers like this: