Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Get the ordinal in fewest characters

 
Rick Beaver
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic