Carlos Nunes
Carlos Nunes

Reputation: 2001

What is the best way to round numbers in Clojure?

This is an easy one. But anyway, I think it is a good idea to have this question answered here for a faster, easier reference.

This operation:

(/ 3 2)

yields this:

3/2

I need one function to round up, which would yield 2 and another one to round down, which would yield 1.

Upvotes: 49

Views: 34794

Answers (6)

N. Syiemlieh
N. Syiemlieh

Reputation: 11

I think this might help if anyone wants a "round to precision" function

(defn round
  "Rounds 'x' to 'places' decimal places"
  [places, x]
  (->> x
       bigdec
       (#(.setScale % places java.math.RoundingMode/HALF_UP))
       .doubleValue))

Sources:

Upvotes: 1

erdos
erdos

Reputation: 3538

Clojure version 1.11 added the new clojure.math namespace with rounding functions. So you no longer need explicit interop:

=> (require '[clojure.math :refer [ceil floor round]])
=> (ceil 3/2)
2.0
=> (floor 3/2)
1.0
=> (round 3/2)
2

Upvotes: 7

You can round also using with-precision function

=> (with-precision 10 :rounding FLOOR (/ 1 3M))
0.3333333333M
=> (with-precision 10 :rounding CEILING (/ 1 3M))
0.3333333334M

https://clojuredocs.org/clojure.core/with-precision

Upvotes: 10

Reb.Cabin
Reb.Cabin

Reputation: 5567

Try this, which produces a pair of the floor and ceiling for non-negative numerator and positive denominator:

(fn [num den] (let [q (quot num den)
                    r (rem  num den)]
                [q (if (= 0 r) q (+ 1 q))])

Upvotes: 1

cfrick
cfrick

Reputation: 37033

You can java interop (Math/(floor|ceil). E.g.:

user=> (int (Math/floor (/ 3 2)))
1
user=> (int (Math/ceil (/ 3 2)))
2

Upvotes: 63

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91554

cast it to the desired type

(int 3/2) 
=> 1
(double 3/2)
=> 1.5
(float 3/2)
=> 1.5

then wrap that in a call to Math.round etc.

user> (Math/round (double 3/2))
2
user> (Math/floor (double 3/2))
1.0
user> (Math/ceil (double 3/2))
2.0

Upvotes: 39

Related Questions