Vertical align floats on decimal dot

2019-06-15 13:47发布

问题:

Is there a simple way to align on the decimal dot a column of floats? In other words, I would like an output like the one of (vertical bars '|' are there only for clarity purpose)

(format t "~{|~16,5f|~%~}" '(798573.467 434.543543 2.435 34443.5))

which is

|    798573.44000|
|       434.54355|
|         2.43500|
|     34443.50000|

but with trailing spaces instead of zeros, as follows:

|    798573.44   |
|       434.54355|
|         2.435  |
|     34443.5    |

回答1:

I do not think that this can easily be done with format's inbuilt control characters, but you could pass your own function to it:

(defun my-f (stream arg colon at &rest args)
  (declare (ignore colon at))
  (destructuring-bind (width digits &optional (pad #\Space)) args
    (let* ((string (format nil "~v,vf" width digits arg))
           (non-zero (position #\0 string :test #'char/= :from-end t))
           (dot (position #\. string :test #'char= :from-end t))
           (zeroes (- (length string) non-zero (if (= non-zero dot) 2 1)))
           (string (nsubstitute pad #\0 string :from-end t :count zeroes)))
      (write-string string stream))))

You can use it like this:

CL-USER> (format t "~{|~16,5/my-f/|~%~}" '(798573.467 434.543543 2.435 34443.5 10))
|    798573.44   |
|       434.54355|
|         2.435  |
|     34443.5    |
|        10.0    |
NIL

The padding character defaults to #\Space, and may be given as a third argument like this: "~16,5,' /my-f/".

An alternative implementation using loop:

(defun my-f (stream arg colon at &rest args)
  (declare (ignore colon at))
  (loop with string = (format nil "~v,vf" (car args) (cadr args) arg)
        and seen-non-zero = nil
        for i from (1- (length string)) downto 0
        as char = (char string i)
        if (char/= char #\0) do (setq seen-non-zero t)
        collect (if (and (not seen-non-zero)
                         (char= char #\0)
                         (not (char= #\. (char string (1- i)))))
                    (or (caddr args) #\Space)
                    char) into chars
        finally (write-string (nreverse (coerce chars 'string)) stream)))

(Disclaimer: Maybe I overlooked something easier in the documentation of format.)