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.

Check out my latest book, the essential, in-depth guide to performance for all .NET developers:

Writing High-Performance.NET Code, 2nd Edition by Ben Watson. Available for pre-order:

3 thoughts on “Easily Getting Last Two Digits of Year

  1. nec

    int lastTwo = year % 100;

    this doesn’t give the last two digits. For 2007, i want 07 but the operation will give me 7.

  2. pepethecow Post author

    nec, to get the zero, in the formatted output you will have to pad it. In C, it would be:

    printf(“%02d”, lastTwo);

    Suppose you have 2027 %100. Then the answer is, correctly, 27.

Leave a Reply

Your email address will not be published. Required fields are marked *