Page 1 of 1

Useful function: ordinal numbers

Posted: Sun Jul 27, 2014 8:40 am
by TedWalther
Since format doesn't print numbers as ordinals, (fault of the underlying printf function) I made a function to do it.

This takes a number, and returns a string in ordinal form.

1 becomes 1st
2 becomes 2nd
3 becomes 3rd
4 becomes 4th

And so on.

Code: Select all

(define (ordinal n)
  (let (nn (string n))
    (cond
      ((regex {1[123]$} nn) (string nn "th"))
      ((regex {1$} nn) (string nn "st"))
      ((regex {2$} nn) (string nn "nd"))
      ((regex {3$} nn) (string nn "rd"))
      ((regex {[4567890]$} nn) (string nn "th"))
      (true nn))))
(global 'ordinal)
I've put this in my init.lsp. Handy little function.

Sample usage:

Code: Select all

> (ordinal 3)
"3rd"
> (ordinal 4)
"4th"
> (ordinal 65)
"65th"
> (ordinal 10)
"10th"
> (ordinal 11)
"11th"
> (ordinal 12)
"12th"
> (ordinal 13)
"13th"
> (ordinal 14)
"14th"
> (ordinal 24)
"24th"
> (ordinal 23)
"23rd"
> (ordinal 21)
"21st"