垂直对齐浮点数小数点

时间:2011-06-15 13:23:45

标签: lisp floating-point format common-lisp vertical-alignment

是否有一种简单的方法可以在小数点上对齐一列浮点数?换句话说,我希望输出像(垂直条'|'仅用于清晰目的)

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

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

但是使用尾随空格而不是零,如下所示:

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

1 个答案:

答案 0 :(得分:5)

我不认为使用format的内置控制字符可以很容易地做到这一点,但你可以将自己的函数传递给它:

(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))))

你可以像这样使用它:

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

填充字符默认为#\Space,可以作为第三个参数给出,如下所示:"~16,5,' /my-f/"

使用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)))

(免责声明:也许我在format的文档中忽略了一些更容易的东西。)