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

haw*_*eye 4 currency clojure number-formatting

我正在使用以下内容:

(defn dollars [input] (str "$" (format "%.2f" input)))
Run Code Online (Sandbox Code Playgroud)

(这不做逗号)

但我想一定有一个使用的方法pprint/cl-format

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

cfr*_*ick 5

如果您需要更多的资金处理工作,而不仅仅是格式化它,您可以考虑使用https://github.com/clojurewerkz/money (请参阅格式化部分),它包含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"
Run Code Online (Sandbox Code Playgroud)

编辑

您可以通过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"
Run Code Online (Sandbox Code Playgroud)