Clojure convert currency string to float
我知道有很多关于将字符串转换为float / number / decimal的问题...但是我的情况大不相同,因为我需要转换字符串号(代表美元值),但是我必须保持此转换中的美分,这是我的情况。
我收到此值
" 96,26 "
" 1.296,26 "
我希望转换为以下内容:
96.26
1296.26
如果我尝试使用clojure.edn,它会逸出美分
1 2 | (edn/read-string"1.296,26") => 1.296 |
1 2 | (edn/read-string"96,26") => 96 |
如果我尝试使用像bugdec这样的其他方法,则会收到NumberFormatException
我知道我们可以做一些字符串替换,但是看起来很麻烦,就像这样:
1 2 3 4 | (->"1.296,87" (clojure.string/replace #"\\.""") (clojure.string/replace #","".") (edn/read-string)) |
您可以做的是使用Java的格式化工具:
1 2 3 4 5 6 7 8 9 | (defn read-num [s] (let [format (java.text.NumberFormat/getNumberInstance java.util.Locale/GERMANY)] (.parse format s))) user> (read-num"1.296,26") ;;=> 1296.26 user> (read-num"96,26") ;;=> 96.26 |
只需使用直接Java互操作即可:
1 2 3 | (let [nf (java.text.NumberFormat/getInstance java.util.Locale/FRENCH)] (.parse nf"12,6")) => 12.6 |
请参阅Oracle文档:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/NumberFormat.html
和此发布:https://www.baeldung.com/java-decimalformat
您也可以获取
1 2 3 4 5 | (let [nf (DecimalFormat."" (DecimalFormatSymbols. Locale/ITALIAN)) >> (.setParseBigDecimal nf true) result (.parse nf"123.45,9")] result => <#java.math.BigDecimal 12345.9M> |