Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numbers to Ordinal format

Status
Not open for further replies.

Ramnarayan

Programmer
Joined
Jan 15, 2003
Messages
56
Location
US
Hi,

I need to write a script to convert numbers to their ordinal form. AN example is given below:

1: 1st
2: 2nd
3: 3rd
4: 4th
5: 5th
6: 6th
7: 7th
8: 8th
9: 9th
0: 0th

For example
3: 3rd
22: 22nd
517: 517th
60: 60th
19993: 19993rd

I searched on the CPAN and could not find any Modules which can facilitate the conversion. I am at a lost on what logic is being used for this. Any useful scripts to generate the output will be greatly appreciated.
 
there might be a module for this for all I know, but here is one way it could be done:

Code:
my @digits = (1 .. 500);
foreach my $n (@digits) {
   if ($n =~ /1$/) {
      $n .= 'st';
   }
   elsif ($n =~ /2$/) {
      $n .= 'nd';
   }
   elsif ($n =~ /3$/) {
      $n .= 'rd';
   }
   else {
      $n .= 'th';
   }
   print "$n\n";
}
 
also nine would become nineth ;-)

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
This is converting numbers, not words..

Code:
foreach (0..500) {
  if( /1[123]$/ ) {
    $ord = 'th';
  } elsif( /1$/ ) {
    $ord = 'st';
  } elsif( /2$/ ) {
    $ord = 'nd';
  } elsif( /3$/ ) {
    $ord = 'rd';
  } else {
    $ord = 'th';
  }
  $out = $_.$ord;
  print "$out\n";
}

Basically it's the same as KevinADC's, but with a check for 11,12,13
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top