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?

Answers


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

Need Your Help

Functional testing tools - Seeking advice

javascript grails selenium webdriver functional-testing

I am currently developping a web application using Grails and JQuery. The project contains some Ajax requests. I would like to choose a functional testing tool and have found information on the sub...

Navigate Programmatically in Windows Media Center

c# windows-7 windows-media-center

I'm developing an Windows Media Center add-in on a Win-7 machine (if that is relevant).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.