Clojure:
Rounding numbers

How to:

In Clojure, we primarily use Math/round, Math/floor, and Math/ceil:

(Math/round 3.5) ; => 4
(Math/round 3.4) ; => 3

(Math/floor 3.7) ; => 3.0
(Math/ceil 3.2)  ; => 4.0

For specific decimal places, we multiply, round, and divide:

(let [num 3.14159
      scale 1000]
  (/ (Math/round (* num scale)) scale)) ; => 3.142

Deep Dive

Before fancy programming languages, rounding was a manual process, think abacus or paper. In programming, it’s crucial for number representation due to floating-point precision limitations.

Alternatives for rounding include using the BigDecimal class for precision control or libraries like clojure.math.numeric-tower for advanced math functions. Clojure’s Math/round relies on Java’s Math.round, Math/floor, and Math/ceil functions, which means it inherits the same float and double nuances.

Implementation-wise, when rounding in Clojure, remember it automatically uses double precision when dealing with decimals. Careful with rounding errors!

See Also