Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Language Basics

Numbers and Arithmetic in Clojure

Learn Clojure numeric types: 64-bit longs, big integers, exact ratios, doubles and big decimals, plus arithmetic functions, overflow rules, mod versus rem and equality.

Clojure's numbers are built on the host platform (Java's numeric tower), with a few friendly additions: exact ratios, automatic arbitrary precision when you ask for it, and arithmetic functions that accept any number of arguments. Understanding the types helps you avoid surprises with overflow and rounding.

The numeric types

Literal Type Notes
42, -7 Long (64-bit integer) The default integer
42N BigInt Unlimited size
3.14, 1e3 Double (64-bit float) The default decimal
3.14M BigDecimal Exact decimal arithmetic
22/7 Ratio Exact fraction
0xFF, 2r1010, 8r17 Long Hex, binary (radix 2), octal

Use type in the REPL to check:

CLOJURE
(type 42)      ; java.lang.Long
(type 42N)     ; clojure.lang.BigInt
(type 3.14)    ; java.lang.Double
(type 3.14M)   ; java.math.BigDecimal
(type 22/7)    ; clojure.lang.Ratio

Arithmetic functions

Arithmetic uses ordinary functions with prefix notation. They accept any number of arguments:

CLOJURE
(+ 1 2 3 4)        ; 10
(- 10 3 2)         ; 5   (10 - 3 - 2)
(- 5)              ; -5  (negation)
(* 2 3 4)          ; 24
(/ 20 2 5)         ; 2
(+)                ; 0   (identity for +)
(*)                ; 1
(inc 9)            ; 10
(dec 9)            ; 8
(max 3 9 4)        ; 9
(min 3 9 4)        ; 3

Because + is a function, you can pass it around: (reduce + [1 2 3]) and (apply + [1 2 3]) both give 6.

Division and ratios

Dividing two integers that do not divide evenly returns an exact ratio instead of rounding:

CLOJURE
(/ 10 4)       ; 5/2
(/ 10 5)       ; 2
(/ 1 3)        ; 1/3
(+ 1/3 1/6)    ; 1/2
(double 5/2)   ; 2.5
(/ 10.0 4)     ; 2.5

Ratios never lose precision, so (* 3 (/ 1 3)) is exactly 1. If you want a floating-point result, make one operand a double or call double.

For whole-number division use quot, rem and mod:

CLOJURE
(quot 17 5)    ; 3     integer quotient (truncates toward zero)
(rem 17 5)     ; 2     remainder (sign follows the dividend)
(mod 17 5)     ; 2
(quot -7 3)    ; -2
(rem -7 3)     ; -1
(mod -7 3)     ; 2     mod follows the sign of the divisor

Use mod for wrap-around calculations such as clock arithmetic, and rem when you want the remainder of truncating division.

JS Stand-in: exact ratios in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Overflow and arbitrary precision

A Long holds numbers up to 9223372036854775807. Clojure does not silently wrap around when you exceed it: ordinary arithmetic throws an ArithmeticException ("integer overflow"). You have two ways to deal with big numbers:

CLOJURE
(+ Long/MAX_VALUE 1)    ; throws: integer overflow
(+' Long/MAX_VALUE 1)   ; 9223372036854775808N  (auto-promotes to BigInt)
(*' 99999999999 99999999999)

(reduce *' (range 1N 26N))   ; 25! as a BigInt: 15511210043330985984000000N

The primed operators +', -', *', inc' and dec' promote to BigInt as needed. Starting from a BigInt literal (such as 1N) is the simplest way to stay in arbitrary precision.

JS Stand-in: Long overflow versus BigInt

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Doubles and exact decimals

Doubles are fast but binary floating-point cannot represent most decimal fractions exactly:

CLOJURE
(+ 0.1 0.2)          ; 0.30000000000000004
(+ 0.1M 0.2M)        ; 0.3M   (BigDecimal is exact)
(rationalize 0.1)    ; 1/10

For money, use integers (cents) or BigDecimal (M suffix). Never use doubles to represent currency.

Special double values exist: Double/NaN, Double/POSITIVE_INFINITY. Check them with Double/isNaN and Double/isInfinite. Dividing an integer by zero throws ((/ 1 0)), but dividing doubles gives infinity ((/ 1.0 0)).

Math functions

The core Math class from Java is available without importing, using Class/method syntax:

CLOJURE
(Math/sqrt 16)       ; 4.0
(Math/pow 2 10)      ; 1024.0
(Math/abs -5.5)      ; 5.5
(Math/floor 2.7)     ; 2.0
(Math/round 2.5)     ; 3
(abs -5)             ; 5   (clojure.core/abs since Clojure 1.11)

Clojure 1.11 also added parse-long and parse-double, which return nil instead of throwing on bad input:

CLOJURE
(parse-long "42")      ; 42
(parse-long "4x2")     ; nil
(parse-double "3.5")   ; 3.5

Equality and comparison

CLOJURE
(= 2 2)            ; true
(= 2 2.0)          ; false  (different categories: integer vs floating point)
(== 2 2.0)         ; true   (== compares numeric value)
(< 1 2 3 4)        ; true   (strictly increasing)
(<= 1 1 2)         ; true
(zero? 0)  (pos? 5)  (neg? -1)  (even? 4)  (odd? 3)

Use = for most comparisons (it also works on collections) and == when you specifically want a numeric comparison across types. Comparison functions accept many arguments, so (< a b c) checks that b lies between a and c.

(= 1 1.0) is false. Mixing integers and doubles as map keys or set members is a common source of bugs. Keep one numeric category per value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (/ 10 4) return in Clojure?

    Integer division that does not divide evenly returns an exact ratio.
  2. 2. What happens with (+ Long/MAX_VALUE 1)?

    Ordinary arithmetic is checked. Use +' to auto-promote to BigInt.
  3. 3. What is (mod -7 3)?

    mod takes the sign of the divisor, giving 2. rem would give -1.
  4. 4. Which expression is true?

    == compares numeric values across types; = also requires the same numeric category.
  5. 5. Which type should you use for exact currency calculations?

    Doubles cannot represent most decimal fractions exactly; BigDecimal and integer cents can.

Summary

  • Default integers are 64-bit Longs; N makes BigInts, M makes BigDecimals, decimals are Doubles.
  • (/ 10 4) returns the exact ratio 5/2; use quot, rem and mod for integer division.
  • Checked arithmetic throws on overflow; +', *' promote to BigInt.
  • Use = for general equality and == for numeric comparison across types.
  • Never use doubles for money.

Next: Strings, Characters, Keywords and Symbols