ColdFusion in Context: Cardinal Numbers
Suppose you have an application that gives users information about the first, second, or twentieth transaction in a batch file. Referring to the transaction as transaction 1 can be confusing; because, the transaction probably has a unique identifier that sure isn't 1. To avoid phone calls on the subject, it would be nice to be able to cite the 3rd transaction in the file instead of transaction 3. That's where this tip comes in.
First, Consider the Topic
Everyday numbers we use in counting are called ordinal numbers. If we want to specify that something is the first or second, we're talking about cardinal numbers. A common abbreviation for such numbers is to add "st", "nd", "rd", or "th" to the ordinal number as appropriate to form the corresponding cardinal number.
Second, Take Action
The suffix we should add depends on the number being modified. An ending of 11 through 13 becomes th. Otherwise, an ending of 1 becomes 1st, of 2 becomes 2nd, of 3 becomes 3rd, and of everything else becomes __th. Put this code in cardinal.cfm. The function shown here takes an ordinal number as its input and returns the corresponding cardinal number. The value function does two things for you here. It returns zero for empty strings and letters. It also puts legitimate numeric strings in a reasonable format, stripping spaces and leading zeroes. You can even pass it an expression.
<cfscript>
function cardinal(Ordinal) {
Work=val(Ordinal);
if (right(Work, 1) is '1') {
if ((len(Work) gt 1) and
(right(Work, 2) gt 10) and
(right(Work,2) lt 14)) {
Work="#Work#th";
}
else {
Work="#Work#st";
}
}
else if(right(Work, 1) is 2) {
Work="#Work#nd";
}
else if(right(Work, 1) is 3) {
Work="#Work#rd";
}
else {
Work=Work&"th";
}
return Work;
}
</cfscript>
Third, View the Result
Once you've included this function, you can use it in output as shown here. Browse cardinal.cfm. In "real life", you would probably use the cardinal function to transform database output to an appropriate display for messages to the user.
<cfoutput>
Yes, one can say #cardinal("anyletters")#, but it sure sounds funny.<br>
Do it right the #cardinal(" 1 x")# time.<br>
We may be the #cardinal(0002)# most popular, but we try harder<br>
The #cardinal(2+1)# time's the charm.<br>
What is the #cardinal(504)# dimension?<br>
Remember September #cardinal(11)#.<br>
Is the #cardinal(21)# a special day for anyone in your family?
</cfoutput>
Integrate this into your own work and share your stories. =Marty=