DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Helper To Print Numbers As Ordinals (1st, 2nd, 3rd...)

08.23.2005
| 14134 views |
  • submit to reddit
        
def number_to_ordinal(num)
  num = num.to_i
  if (10...20)===num
    "#{num}th"
  else
    g = %w{ th st nd rd th th th th th th }
    a = num.to_s
    c=a[-1..-1].to_i
    a + g[c]
  end
end

number_to_ordinal(12) => "12th"
number_to_ordinal(7) => "7th"

Note that floats will be converted to ints (without rounding) before processing.      

Comments

Claudio Petasec... replied on Thu, 2009/02/05 - 6:05am

class Integer def ordinal to_s + ([[nil, 'st','nd','rd'],[]][self % 100 / 10 == 1 ? 1 : 0][self % 10] || 'th') end end

Snippets Manager replied on Sun, 2009/01/25 - 6:48pm

Actually this is now built in to the framework: It is the <%= Time.now.ordinalize %> day of the month

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

In case that didn't work for you, here's my version: class Numeric def ordinal self.to_s + ( (10...20).include?(self) ? 'th' : %w{ th st nd rd th th th th th th }[self % 10] ) end end

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

Or even: class Numeric def ordinal self.to_s + ( 10...20 === self ? 'th' : %w{ th st nd rd th th th th th th }[self[-1]] ) end end

Snippets Manager replied on Mon, 2012/05/07 - 2:14pm

How about class Numeric def ordinal (10...20) === self ? "#{self}th" : self.to_s + %w{ th st nd rd th th th th th th }[self.to_s[-1..-1].to_i] end end p 2.ordinal p 20.ordinal p 23.ordinal p (0xA8).ordinal