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.

Popularity: 4% [?]

  1. 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. 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.

  3. yeah, i know. just pointing out that it’s not a single expression as i see that post as a tutorial.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>