Search code examples
clojurestring-parsing

Clojure convert currency string to float


I know that there's a lot of questions about converting string to float/number/decimal... but my case is quite different cause I need to convert the string number (representing a dollar value) but I must keep the cents in this conversion, here is my case.

I receive this values "96,26" "1.296,26" And I expect to convert to this follow: 96.26 1296.26

If I try to use clojure.edn it escape cents

(edn/read-string "1.296,26")
=> 1.296
(edn/read-string "96,26")
=> 96

If I try to use another approach like bugdec I get NumberFormatException

I know that we can do some string replace but it looks like a big work around, like this:

(-> "1.296,87"
    (clojure.string/replace #"\." "")
    (clojure.string/replace #"," ".")
    (edn/read-string))

Solution

  • what you can do, is to use java's formatting facilities:

    (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