【问题标题】:Formatting floating point numbers without printing zeros after decimal point格式化浮点数而不在小数点后打印零
【发布时间】:2011-11-30 23:07:43
【问题描述】:

我想以好看的方式打印花车。具体来说,我想在小数点后打印两个数字,但前提是这些数字不为零。

如果数字不是偶数,则此方法有效:

(let ((f 1.240))
  (format t "~,2F" f))

--> 1.24 

但如果数字是整数,我会得到:

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

-->1240.00

是否有一些优雅的方法可以做到这一点,或者我必须在打印之前手动检查小数点的数量?

【问题讨论】:

    标签: string lisp format common-lisp


    【解决方案1】:

    我认为这对于标准格式指令是不可能的。您可以编写自定义格式函数:

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

    并像这样使用它:

    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
    

    【讨论】:

      【解决方案2】:

      您可以使用 FORMAT 条件表达式:

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

      【讨论】:

      • (let ((f 1.1)) (format t "~:[~,2f~;~d~]" (integerp f) f)) 打印 1.10,但他不想要尾随零。再一次,他写道“只有当这些数字s 不为零时”,所以从技术上讲,你仍然符合规范。 :)
      猜你喜欢
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多