In Clojure how can I convert a String to a number?

appshare.co picture appshare.co · Apr 11, 2011 · Viewed 84.1k times · Source

I have various strings, some like "45", some like "45px". How how I convert both of these to the number 45?

Answer

Benjamin Atkin picture Benjamin Atkin · Feb 8, 2012

New answer

I like snrobot's answer better. Using the Java method is simpler and more robust than using read-string for this simple use case. I did make a couple of small changes. Since the author didn't rule out negative numbers, I adjusted it to allow negative numbers. I also made it so it requires the number to start at the beginning of the string.

(defn parse-int [s]
  (Integer/parseInt (re-find #"\A-?\d+" s)))

Additionally I found that Integer/parseInt parses as decimal when no radix is given, even if there are leading zeroes.

Old answer

First, to parse just an integer (since this is a hit on google and it's good background information):

You could use the reader:

(read-string "9") ; => 9

You could check that it's a number after it's read:

(defn str->int [str] (if (number? (read-string str))))

I'm not sure if user input can be trusted by the clojure reader so you could check before it's read as well:

(defn str->int [str] (if (re-matches (re-pattern "\\d+") str) (read-string str)))

I think I prefer the last solution.

And now, to your specific question. To parse something that starts with an integer, like 29px:

(read-string (second (re-matches (re-pattern "(\\d+).*") "29px"))) ; => 29