Wednesday, July 30, 2008

Ordinal Numbers in Flash

We use ordinal numbers all the time, even though we may not always appreciate what they are, or why we're using them.

An ordinal number reflects the rank of that number in a particular order, or its position. So we might use expressions like "he came first in the race", or "that's the third bus to come along in the past hour", or "today is the thirtieth of July". When we write down ordinal numbers we use shorthand, so first becomes 1st, third becomes 3rd, and thirtieth becomes 30th.

Here's a (relatively) simple function that can calculate the ordinal for any given number in Flash:

function getOrdinalNumber(num) { 
return num==0 ? num : num + ['th', 'st', 'nd', 'rd'][!(num % 10 > 3 || Math.floor(num % 100 / 10) == 1) * num % 10];

Using the function is straightforward:

// returns 11th
trace("Today is Thursday " + getOrdinalNumber(7) + " February");
// returns Today is Thursday 7th February
for(i=0; i<=120; i++){
// returns all of the ordinal numbers from 1 to 120

No comments: