Clojure: Numbers

By Xah Lee. Date: . Last updated: .

Numbers can be written in the form

baserdigits

For example, the binary number 10 can be written as 2r10, and the hexadecimal 1a can be written as 16r1a

;; binary number input
2r1111 ;  15

;; hexadecimal number input
16r1af ;  431
0x1af ;  431  (this form is from Java)

;; oct number input
8r77 ;  63

;; base 36. using 0 to and a to z as digits
36rj7 ;  691

Arithmetic

;; addition, plus
(+ 3 4)

;; substraction, minus
(- 7 4)

;; can have 3 or more args
(- 7 4 1)

;; multiply, times
(* 2 4)

Here's division, quotient, remainder/mod, and ratio.

;; division
(/ 7 4) ; 7/4  return a ratio. A Clojure datatype

(/ 7 4.) ; 1.75

;; integer quotient
(quot 11 4) ; 2

;; remainder (aka mod)
(rem 11 4) ; 3

Closure does not have a math lib bundled.

To use math function such as sine, use Java's Math class. Like this: (Math/methodName arg)

;; exponentiation. 2 to the power of 3
(Math/pow 2 3) ;  8.0

[see Clojure: Call Java Method]

Converting String and Numbers

;; convert string to number
(bigint "123")

there is also

;; convert number to string
(str 123)

Codepoint to Character

;; unicode codepoint (integer) to char
(char 97) ; a

Number Comparison Functions

(< 3 7) ; true

(<= 3 7) ; true

(> 3 7) ; false

(>= 3 7) ; false

Check on Number