【问题标题】:How to idiomatically print currency in Clojure?如何在 Clojure 中惯用地打印货币?
【发布时间】:2015-04-15 09:59:59
【问题描述】:

我正在使用以下内容:

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

(不使用逗号)

但我认为必须有使用pprint/cl-format的方法。

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

【问题讨论】:

    标签: clojure currency number-formatting


    【解决方案1】:

    如果您有更多关于金钱的工作,而不仅仅是格式化它,您可以考虑使用 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"
    

    编辑

    你可以通过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)) ArithmeticException 金额 1181.2442721929447 的比例大于货币美元的规模 org.joda.money.Money.of (Money.java:74)
    • @hawkeye 查看编辑,您可以将舍入模式传递给amount-of
    【解决方案2】:

    另见银行家: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"
    

    【讨论】:

      猜你喜欢
      • 2011-01-23
      • 2011-04-30
      • 2023-04-04
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多