【问题标题】:In ClojureScript, how to display a float with 2 decimals?在 ClojureScript 中,如何显示带有 2 位小数的浮点数?
【发布时间】:2014-02-04 13:42:45
【问题描述】:

我曾尝试使用with-precision,但没有成功:

(.log js/console (with-precision 2 1.2345)) 

所以我用了toFixed:

(.log js/console (.toFixed 1.2345 2)) 

但我觉得这不是惯用的方式。

另外,我不明白为什么with-precision 不起作用。

请启发我...

【问题讨论】:

标签: clojurescript


【解决方案1】:
(ns foo.bar
  (:require
    [goog.string :as gstring]
    [goog.string.format]))

(.log js/console (gstring/format "%.2f" 1.2345))

【讨论】:

  • 有趣的是 Google 关闭 specifically says 以在简单的情况下使用 .toFixed
  • 是的,我认为.toFixed 更适合这个例子。正确的答案似乎是“你做得对”:)
【解决方案2】:
(ns foo.bar
  (:require [cljs.pprint :as pprint]))

(pprint/cl-format nil  "~,2f" 1.2345) ; => returns "1.23"
(pprint/cl-format true "~,2f" 1.2345) ; => prints "1.23", returns nil

如果您将cljs.pprintclojure.pprint 交换,则可以在Clojure 中使用相同的代码。

【讨论】:

    【解决方案3】:
    (defn round-number 
       [f]
       (/ (.round js/Math (* 100 f)) 100))
    

    如果你想保持为数字类型(灵感来自javascript reply

    【讨论】:

      猜你喜欢
      • 2011-09-03
      • 2011-02-02
      • 2021-05-07
      • 2011-03-10
      • 2016-10-19
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      相关资源
      最近更新 更多