Saturday, April 12, 2008

Ordinal Numbers

This week we're going to write a function to turn a cardinal integer into an ordinal number (eg. 4 becomes 4th). This is mostly useful when generating a page to display to a visitor.


ASP

  1. function ordinal(ByVal cardinal)
  2.     cardinal = CStr(cardinal)
  3.     if Right(cardinal, 1) = "1" and Right(cardinal, 2) <> "11" then
  4.         ordinal = cardinal & "st"
  5.     elseif Right(cardinal, 1) = "2" and Right(cardinal, 2) <> "12" then
  6.         ordinal = cardinal & "nd"
  7.     elseif Right(cardinal, 1) = "3" and Right(cardinal, 2) <> "13" then
  8.         ordinal = cardinal & "rd"
  9.     else
  10.         ordinal = cardinal & "th"
  11.     end if
  12. end function

PHP

  1. function ordinal($cardinal)
  2. {
  3.     if (substr($cardinal, -1, 1) == 1 && substr($cardinal, -2, 2) != 11)
  4.     {
  5.         return ($cardinal . 'st');
  6.     }
  7.     elseif (substr($cardinal, -1, 1) == 2 && substr($cardinal, -2, 2) != 12)
  8.     {
  9.         return ($cardinal . 'nd');
  10.     }
  11.     elseif (substr($cardinal, -1, 1) == 3 && substr($cardinal, -2, 2) != 13)
  12.     {
  13.         return ($cardinal . 'rd');
  14.     }
  15.     else
  16.     {
  17.         return ($cardinal . 'th');
  18.     }
  19. }

No comments: