Daily Archives: November 2, 2007

Easily Getting Last Two Digits of Year

This is an easy one, but some people don’t know it: if you need the last two digits of a year, say 2007, it’s very easy to get, without converting to a string and getting the last two characters:

 

int lastTwo = year % 100;

Now that you know, it’s obvious, right?

And if you want the last three digits? number % 1000. In general:

int lastN = number % (pow(10, digitsRequired));

What about first N digits? similarly easy:

 

int firstTwo = number / 100;
int firstN = number / pow(10,digitsRequired);

 
Now  you know, and knowing if half the battle.