I would like format to output ordinal numbers, eg 1st, 243rd, 15th. I
already found "~:r", eg
(format nil "~:r" 3) => third
but I need numbers, not text. I realize this would be quite easy to
hack together with rem and cond, but I suspect that there is a format
way...
Tamas
Tamas Papp <······@gmail.com> writes:
> I would like format to output ordinal numbers, eg 1st, 243rd, 15th. I
> already found "~:r", eg
>
> (format nil "~:r" 3) => third
>
> but I need numbers, not text. I realize this would be quite easy to
> hack together with rem and cond, but I suspect that there is a format
> way...
I don't think there is a way to do this in format, but it's not hard
to do:
(defun ordinal (stream integer colon atsign)
(declare (ignore colon atsign))
(let ((ordinal (format nil "~:R" integer)))
(format stream "~D~A" integer (subseq ordinal (- (length ordinal) 2)))))
CL-USER> (format nil "~/ordinal/" 5)
"5th"
--
RmK
Richard M Kreuter <·······@progn.net> writes:
> Tamas Papp <······@gmail.com> writes:
>
>> I would like format to output ordinal numbers, eg 1st, 243rd, 15th. I
>> already found "~:r", eg
>>
>> (format nil "~:r" 3) => third
>>
>> but I need numbers, not text. I realize this would be quite easy to
>> hack together with rem and cond, but I suspect that there is a format
>> way...
>
> I don't think there is a way to do this in format, but it's not hard
> to do:
>
> (defun ordinal (stream integer colon atsign)
> (declare (ignore colon atsign))
> (let ((ordinal (format nil "~:R" integer)))
> (format stream "~D~A" integer (subseq ordinal (- (length ordinal) 2)))))
>
> CL-USER> (format nil "~/ordinal/" 5)
> "5th"
Hi Richard,
I came up with this:
(defun ordnum (i)
(format nil "~d~a"
i
(case i
((11 12) "th")
(t (case (rem i 10)
((1) "st")
((2) "nd")
((3) "rd")
(t "th"))))))
but I was checking if it was in format lest I reinvent the wheel
(which happens so frequently with me when programming in CL, it is a
well-engineered but extensive language).
Anyhow, I realize I have been swamping the list with questions today,
thanks everyone for the patience and the answers.
Tamas
* Tamas Papp <··············@pu100877.student.princeton.edu> :
| (defun ordnum (i)
| (format nil "~d~a"
| i
| (case i
| ((11 12) "th")
| (t (case (rem i 10)
| ((1) "st")
| ((2) "nd")
| ((3) "rd")
| (t "th"))))))
This breaks on 112 for example.
Heres the function from my personal library which tries to fix that:
(defun ordnum (n)
(write n)
(write-string
(if (<= 11 (setq n (abs (rem n 100))) 20)
"th"
(case (rem n 10)
(1 "st") (2 "nd") (3 "rd") (t "th")))))
| but I was checking if it was in format lest I reinvent the wheel
| (which happens so frequently with me when programming in CL, it is a
| well-engineered but extensive language).
--
Madhu