我知道关于将字符串转换为浮点数/数字/小数有很多问题...但是我的情况大不相同,因为我需要转换字符串数(代表美元值),但是在转换中我必须保留美分,这是我的情况。
我收到此值“ 96,26”“ 1.296,26”并且我希望转换为以下形式:96.26 1296.26
如果我尝试使用clojure.edn,它会逃脱
(edn/read-string "1.296,26")
=> 1.296
(edn/read-string "96,26")
=> 96
如果我尝试使用像bugdec这样的其他方法,则会得到NumberFormatException
我知道我们可以做一些字符串替换,但是看起来很麻烦,就像这样:
(-> "1.296,87"
(clojure.string/replace #"\." "")
(clojure.string/replace #"," ".")
(edn/read-string))
您可以做的是使用Java的格式化工具:
(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
确实要挑剔,双精度浮点表示形式96.26可能不完全是96.26。为了获得值96.26 的精确表示,可以使用诸如的函数将其转换为比率
(defn fraction-of-100 [x] (/ (Math/round (* 100 x)) 100))
。尝试例如
(- 96.26 (- (+ 96.26 100000) 100000))
在REPL中。查看,
DecimalFormat
以及DecimalFormatSymbols
是否需要确切的值。