Formatting floating point numbers without print zeros after the decimal point

I want to print floats in a good way. In particular, I want to print two numbers after the decimal point, but only if these numbers are not equal to 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 the following:

 (let ((f 1240)) (format t "~,2F" f)) -->1240.00 

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

+4
source share
2 answers

I do not think this is possible with standard directives. You can 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 as follows:

 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 
+3
source

You can use the FORMAT conditional expression:

 (let ((f 1240)) (format t "~:[~,2f~;~d~]" (integerp f) f)) --> 1240 
0
source

Source: https://habr.com/ru/post/1384004/


All Articles