Coerce to int
user=> (int 1) 1 user=> (int 1M) 1 user=> (int 1.2) 1 user=> (int \1) 49 user=> (int \a) 97 ;; Strings cannot be cast to an int. user=> (int "1") Execution error (ClassCastException) at user/eval175 (REPL:1). java.lang.String cannot be cast to java.lang.Character ;; Use Java interop instead (Integer/parseInt "1") ;;=> 1 ;; Using JavaScript interop for ClojureScript (js/parseInt "5") ;;=> 5 (js/parseInt "5.22") ;;=> 5
To convert a string containing a number to an integer, use Java's Integer/parseInt, e.g. (Integer/parseInt "-10")
.
The int
function fails to convert a float to a clojure.lang.BigInt
. For example (int (* 1.0 111111111111111111))
fails with an IllegalArgumentException
exception.
Here is a suggestion to work around this limitation.
(letfn [(-int [x] (try (int x) (catch IllegalArgumentException _ (bigint x)) (catch ArithmeticException _ (bigint x))))] (-int (ceil (sqrt 22056254169643100399065378))))
which evaluates to the BitInt
4696408645939N.