[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: formatting numbers



At 2:36 PM 2/23/95, balls@medcolpa.edu wrote:
>I was hacking through a fast way to accomplish printing of atomic
>weights to a periodic table depending upon screen size. In the
>example below a maximum of 5 significant figures should print if
>& only if 5 figures are significant, otherwise 4 or less figures
>should print, depending upon whether or not 4 figures are significant.
>
>(dolist (element/aw '((thallium 204.383)
>                      (barium 137.33)
>                      (osmium 190.2)
>                      (francium 223)))
>  (let ((element (first element/aw))
>        (aw (second element/aw)))
>    (format t "~%~A: " element)
>    (format t (cond ((integerp aw) "~A")
>                    ((/= aw (read-from-string (format nil "~5,1F" aw)))
>                     "~5,2F")
>                    (t "~4,1F"))
>            aw)))
>
>THALLIUM: 204.38
>BARIUM: 137.33
>OSMIUM: 190.2
>FRANCIUM: 223
>NIL
>? 
>
>This is the desired behavior, but it seems a bit contrived.
>Is there not a more simple & more efficient way to do this?
>
>Thanks, Sheldon
>
>
>Sheldon S. Ball
>BALLS@ccc.medcolpa.edu

How about:

(dolist (element/aw '((thallium 204.383)
                      (barium 137.33)
                      (osmium 190.2)
                      (francium 223)))
  (let ((element (first element/aw))
        (aw (second element/aw)))
    (format t "~%~A: " element)
    (cond ((integerp aw) (format t "~A" aw))
          (t (format t "~F" (/ (round aw 1/100) 100))))))

You may want to use TRUNCATE or FLOOR in place of ROUND.

- Steve Hain

Digitool, Inc.
______________________________________________________________________________
                          675 Massachusetts Avenue   Cambridge, MA 02139   USA
                              Internet: slh@digitool.com   AppleLink: digitool
                                         Tel: 617 441-5000   Fax: 617 576-7680
                                                 URL: http://www.digitool.com/