This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programming Diversions and the fly likes Get the ordinal in fewest characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Get the ordinal in fewest characters" Watch "Get the ordinal in fewest characters" New topic
Author

Get the ordinal in fewest characters

Rick Beaver
Ranch Hand

Joined: Dec 14, 2004
Posts: 464
Saw a discussion on another forum about writing a function for getting the ordinal string for a number in the fewest characters. They were doing it in JavaScript but I thought someone might find it worth a go in Java...

I thought I had it with this - until I realised that it doesn't take into account 11th, 12th, 13th (or 111th 112th etc...).



Anyone got any ideas?
[ February 16, 2005: Message edited by: Rick Beaver ]

ph34r my 133t j4v4 h4><0r1ng sk177z
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
return new String[]{"rd","st","nd","th"}[(i-1)%10>2||i%100/5==2?3i%10)%3];

edited to disable smileys
[ February 16, 2005: Message edited by: Michael Dunn ]
Rick Beaver
Ranch Hand

Joined: Dec 14, 2004
Posts: 464
I sneaked a look at the JS solution - they used Math.floor like this - quite clever i thought


[ February 17, 2005: Message edited by: Rick Beaver ]
 
Consider Paul's rocket mass heater.
 
subject: Get the ordinal in fewest characters