Web Development for 2012

Alexander Dickson - Web Developer covering PHP, jQuery / Javascript, XHTML, CSS, more

Using C to get a place suffix

Published on Thursday, 21st October 2010.

Sometimes, we want the place suffix for a number, e.g. when we pass a function 2, we expect nd. Perfect little C function!

char *getPlaceSuffix(int number) { static char *suffixes[] = {"th", "st", "nd", "rd"}; if (number >= 11 && number <= 13) { return suffixes[0]; } else {   number %= 10;   if (number >= 1 && number <= 3) { return suffixes[number]; } else { return suffixes[0]; } }

I've updated my original version - after getting a decent night's sleep and some feedback from Stack Overflow.

I noticed the numbers 11-13 inclusive don't follow the usual convention (well at least not when I say them aloud). I allowed (ha!) for this.

That completes another remotely useful C function!

Comments

  • Nick

    Posted on Saturday, 5th November 2011 @ 10:12am.

    Close, but you forgot this line right after the array declaration:
    number %= 100;

    Call it with number = 5413 to see what I mean.

    Thanks for jquery.inputlabel! That's how I found this blog.

  • Ryan O'Hara

    Posted on Monday, 5th September 2011 @ 6:41am.

    One more small problem - passing 111 returns "st", but it should be "th", so just change the first statement:

    if(number / 10 % 10 == 1) {

  • anonymous coward

    Posted on Tuesday, 10th May 2011 @ 5:42pm.

    Why so many elses?

    After each return, the function is over. Adding an else is an unnecessary increase of the code complexity. And it made you forget a closing } .

  • Michael H

    Posted on Thursday, 3rd March 2011 @ 3:24pm.

    This function gives the wrong answer. 113 should be "113th," but this function would mod 113 by 10, resulting in a 3, which would then return suffix[3], which is "rd", forming "113rd", forming "113rd".

    Please see my answer on StackOverflow for the fix: http://stackoverflow.com/questions/3988373/what-is-the-best-way-to-get-right-most-number-in-an-integer-with-c/5176969#5176969

  • Alexander Dickson

    Posted on Wednesday, 10th November 2010 @ 7:32pm.

    @Jon Rodriguez Thanks for the tip! I probably should of looked at that piece of code more closely. I'll make an update :)

  • Jon Rodriguez

    Posted on Wednesday, 10th November 2010 @ 5:17pm.

    while (number > 10) {
    number % 10;
    }

    should just be

    number %= 10;

Leave a Comment

Comment Details

Your email will never be displayed. If you have a gravatar, it will be displayed.

Note: Your comment may require approval before it is posted to the site.

Stack Overflow Profile

view full profile »

About

I'm a web developer from the Sunshine Coast, Australia. more »