Database Reference
In-Depth Information
To write this function, we just need to have access to the clojure.string library:
(require '[clojure.string :as string])
How to do it…
1.
The function itself is pretty short, shown as follows:
(defn normalize-number [n]
(let [v (string/split n #"[,.]")
[pre post] (split-at (dec (count v)) v)]
(Double/parseDouble (apply str (concat pre [\.] post)))))
2.
Also, using the function is straightforward:
user=> (normalize-number "1,000.00")
1000.0
user=> (normalize-number "1.000,00")
1000.0
user=> (normalize-number "3.1415")
3.1415
How it works…
This function is fairly simple. So, let's take it apart, step by step:
1.
We take the input and use a regular expression to split it on every comma and
period. This handles both the thousands separators and decimals for most locales,
expressions that use comma for thousands and periods for decimals, and vice versa:
(string/split n #"[,.]")
2.
We take the split input and partition it into the integer part (everything up to the last
element) and the fractional part (the last element):
(split-at (dec (count v)) v)
3.
We join them back together as a new string, using a period for the decimal and
leaving out any thousands separators:
(apply str (concat pre [\.] post))
4.
We use the standard Java Double class to parse this into a double :
(Double/parseDouble …)
This version of the function assumes that the numbers are represented with a decimal
component. If that's not the case, there will be problems:
user=> (normalize-number "1,000")
1.0
 
Search WWH ::




Custom Search