ClojureDocs

Nav

Namespaces

int

clojure.core

Available since 1.0 (source)
  • (int x)
Coerce to int
1 Example
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
See Also

Coerce to char

Added by Ljos

Coerce to long

Returns true if n is an integer

Casts to int[]

Creates an array of ints

Coerce to short

3 Notes
    By , created 6.8 years ago

    To convert a string containing a number to an integer, use Java's Integer/parseInt, e.g. (Integer/parseInt "-10").

    By , created 1.4 years ago, updated 1.4 years ago

    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.

    By , created 258 days ago

    Beware, the int function truncates and does not round:

    => (int 15538.999999999998)
    15538