Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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

like image 424
yazz.com Avatar asked Apr 11 '11 12:04

yazz.com


People also ask

How do I convert a string to a number?

The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number. If the string value cannot be converted into a number then the result will be NaN .

What is the fastest way to convert a string to a number?

Converting strings to numbers is extremely common. The easiest and fastest (jsPerf) way to achieve that would be using the + (plus) operator. You can also use the - (minus) operator which type-converts the value into number but also negates it.

How do I convert a string to a number in node?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


2 Answers

This will work on 10px or px10

(defn parse-int [s]    (Integer. (re-find  #"\d+" s ))) 

it will parse the first continuous digit only so

user=> (parse-int "10not123") 10 user=> (parse-int "abc10def11") 10 
like image 126
jhnstn Avatar answered Oct 24 '22 16:10

jhnstn


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 
like image 45
Benjamin Atkin Avatar answered Oct 24 '22 17:10

Benjamin Atkin