没有cl格式的小数位(lisp格式)

时间:2016-11-25 14:01:24

标签: clojure string-formatting clojurescript

我想创建一个函数来格式化一个具有我想要的小数位数的数字。这是我cl-format的尝试:

=> (defn f [decimal-places n] (clojure.pprint/cl-format nil (str "~" decimal-places ",0$") n))
#'core/f
=> (f 5 55)
"55.00000"
=> (f 4 55)
"55.0000"
=> (f 3 55)
"55.000"
=> (f 2 55)
"55.00"
=> (f 1 55)
"55.0"
=> (f 0 55)
"55."

注意最后一个,小数点为零。我基本上是这样做的:

=> (clojure.pprint/cl-format nil "~0,0$" 55)
"55."

它有十进制分隔符 - 一个点 - 在那里。如何使它简单地渲染" 55" (没有点),我可以轻松地(比如我的示例中的str)使其与大于0的decimal-places一起使用?

1 个答案:

答案 0 :(得分:3)

虽然cl-format支持分支,但在这种情况下我会坚持使用简单的if,因为格式的参数在两种情况下实际上都是完全不同的:

(defn f [decimal-places n]
  (if (zero? decimal-places)
      (clojure.pprint/cl-format nil "~D" (Math/round n))
      (clojure.pprint/cl-format nil "~v$" decimal-places n)))

我将n舍入到最接近的整数,而不是仅用(int n)截断。

另一种方法是删除格式化字符串末尾的任何点字符:

(defn undot [string]
  (if (clojure.string/ends-with? string ".")
      (subs string 0 (- (count string) 1))
      string))

(defn f [decimal-places n]
  (undot (clojure.pprint/cl-format nil "~v$" decimal-places n)))
相关问题