Q:

Formatting floating point numbers without printing zeros after decimal point

I want to print floats in a good looking way. Specifically I want to print two numbers after the decimal point, but only if these numbers are not zero.
This works if the number is not an even integer:
(let ((f 1.240))
  (format t "~,2F" f))

--> 1.24 

But if the number is an integer I get this:
(let ((f 1240))
  (format t "~,2F" f))

-->1240.00

Is there some elegant way to do this, or do I have to check the number of decimal points manually before printing out?

A:

I don't think this is possible with standard format directives. You could write a custom format function:
(defun my-f (stream arg &optional colon at digits)
  (declare (ignore colon at))
  (prin1 (cond ((= (round arg) arg) (round arg))
               (digits (float (/ (round (* arg (expt 10 digits)))
                                 (expt 10 digits))))
               (t arg))
         stream))

And use it like this:
CL-USER> (format t "~/my-f/" 1)
1
NIL
CL-USER> (format t "~/my-f/" 1.0)
1
NIL
CL-USER> (format t "~/my-f/" pi)
3.141592653589793D0
NIL
CL-USER> (format t "~/my-f/" 1.5)
1.5
NIL
CL-USER> (format t "~2/my-f/" 1)
1
NIL
CL-USER> (format t "~2/my-f/" 1.0)
1
NIL
CL-USER> (format t "~2/my-f/" pi)
3.14
NIL
CL-USER> (format t "~2/my-f/" 1.5)
1.5
NIL

