There are probably many different ways of doing this, using an assortment of if, case, and switch statements. But here’s the method I use…hope it proves useful to someone:
function getOrdinalNumber(num) {
return num==0 ? num : num + ['th', 'st', 'nd', 'rd'][!(num % 10 > 3 || Math.floor(num % 100 / 10) == 1) * num % 10];
}
Here’s a few samples:
trace(getOrdinalNumber(11));
// returns 11th
trace("Today is Thursday " + getOrdinalNumber(7) + " February");
// returns Today is Thursday 7th February
trace("If the " + getOrdinalNumber(99) + " runner in the marathon is overtaken twice, he slips back to " + getOrdinalNumber(99 + 2) + " place");
// returns If the 99th runner in the marathon is overtaken
// twice, he slips back to 101st place
for(i=0; i<115; i++){
trace(getOrdinalNumber(i));
}
If you’re planning to use it to append an ordinal suffix to dates only, you can shorten the function slightly:
function getOrdinalNumber(num) {
return num + ['th', 'st', 'nd', 'rd'][!(num % 10 > 3 || Math.floor(num % 100 / 10) == 1) * num % 10];
}
And another sample using just dates:
for(i=1; i<32; i++){
trace(getOrdinalNumber(i));
}