Clojure 'if' never evaluating its third argument

I have been trying to figure this out for a while now.

(defn is-decimal [astr] (if (. astr (indexOf (int \.))) (Double/parseDouble astr) (Integer/parseInt astr))) 

This is the function I wrote. is-decimal is passed something like "2.5" or "5" or something like that, but always uses the second if argument, not the third. I tested (. astr (indexOf (int \.))) In REPL and it seems to work fine, it returns -1 when it fails, and 1 when it doesn't. I think this could be a problem. -1 does not mean false in Clojure. Can anyone think about how to fix this?

Thanks in advance.

EDIT: Thanks for helping the guys. Immediately after I wrote this, I had an idea. I wrote a predicate function that checks 1 and -1. Just what I needed. I should not code immediately after waking up: \

+7
clojure
source share
3 answers

If you want to check if a string contains a character, you can use a regular expression:

 (re-find #"\." astr) 

Or:

 (some #(= \. %) astr) 

Or:

 (contains? (into #{} astr) \.) 

Or can you use includes? from clojure.contrib.seq-utils , which does this too.

Clojure already has a reader who knows how to distinguish between ints and double, so if you are sure that your string contains only numbers, you can use it. (Be careful though it reads anything, not just numbers. This is potentially dangerous. Do not use this if it is possible that your line has something other than a number.)

Note. Clojure also handles the case where an integer is too large to fit into a native int without overflow. If you want to parse integers, you might need the bigint function, not parseInt .

 user> (class (read-string "2.5")) java.lang.Double user> (class (read-string "2")) java.lang.Integer user> (class (read-string "2000000000000")) java.math.BigInteger 

If your function is a predicate, is it commonly used in Clojure to denote its decimal? , not is-decimal . Your function is actually more than a number parser, so personally I would call it parse-number or string-to-number .

+10
source share

Unverified:

 (if (> 0 (. astr (indexOf (int \.)))) 
+6
source share

Well, if it returns -1, if it does not work, then check the value -1 and return false if it

+2
source share

All Articles