如何在 Clojure 中以惯用的方式打印货币?

How to idiomatically print currency in Clojure?

我正在使用以下内容:

(defn dollars [input] (str "$" (format "%.2f" input)))

(没有逗号)

不过我觉得一定有方法用pprint/cl-format

我的问题是:如何在 Clojure 中以惯用的方式打印货币?

如果你有更多的钱要处理,而不仅仅是格式化它,你可以考虑使用 https://github.com/clojurewerkz/money(参见 格式化 部分),它包含 joda-money.这不仅包括格式设置,还包括其他常见问题,如舍入。

user=> (mf/format (ma/amount-of mc/USD 10000))
",000.00"
user=> (mf/format (ma/amount-of mc/USD 10000) java.util.Locale/GERMANY)
"USD10.000,00"

编辑

可以通过amount-of四舍五入的方式。例如

user=> (mf/format (ma/amount-of mc/USD 10.111111111111111))

ArithmeticException Scale of amount 10.11111111111111 is greater than the scale of the currency USD  org.joda.money.Money.of (Money.java:74)

user=> (mf/format (ma/amount-of mc/USD 10.111111111111111 (java.math.RoundingMode/HALF_DOWN)))
".11"

另见 Bankster:https://github.com/randomseed-io/bankster

(money/of :EUR 25)
; => #money[25.00 EUR]

(money/of 25 :EUR)
; => #money[25.00 EUR]

(money/of crypto/BTC 10.1)
; => #money/crypto[10.10000000 BTC]

(money/of BTC 10.1)
; => #money/crypto[10.10000000 BTC]

#money EUR
; => #money[0.00 EUR]

#money/crypto ETH
; => #money/crypto[0.000000000000000000 ETH]

#money[PLN 2.50]
; => #money[2.50 PLN]

#currency USD
; => #currency{:id :USD, :domain :ISO-4217, :kind :FIAT, :numeric 840, :scale 2}

(currency/symbol :USD)
; => "USD"

(currency/symbol :USD :en_US)
; => "$"

(currency/symbol :USDT)
; => "₮"

(currency/name :USDT)
; => "Tether"

(money/format #money[10 EUR])
; => "10,00 €"

(money/format #money[10 EUR] :en_US)
; => "€10.00"

(money/format #money[10 EUR] :pl {:currency-symbol-fn currency/name})
; => "10,00 euro"