如何在Clojure中习惯性地打印货币?

4
我将使用以下内容:

我正在使用以下内容:

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

(这种方法不会输出逗号)

但我认为可以使用pprint/cl-format方法。

我的问题是:如何在Clojure中习惯性地打印货币?

2个回答

5
如果你需要处理货币金额的其他问题而不仅仅是格式化,可以考虑使用 https://github.com/clojurewerkz/money (参见 Formatting 部分),它是基于 joda-money 的封装。这不仅涵盖了格式化,还包括了舍入等其他常见问题。
user=> (mf/format (ma/amount-of mc/USD 10000))
"$10,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)))
"$10.11"

这个选项似乎不具备可扩展性: core=> (format (clojurewerkz.money.amounts/amount-of clojurewerkz.money.currencies/USD 1181.2442721929447))算术异常:金额 1181.2442721929447 的精度大于货币 USD 的精度 org.joda.money.Money.of (Money.java:74) - hawkeye
@hawkeye 看编辑,你可以向 amount-of 传递一个舍入模式。 - cfrick

2
另请参见 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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接