45

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.

Rodrigo Taboada
  • 2,727
  • 4
  • 24
  • 27
Carlos Nunes
  • 1,929
  • 2
  • 16
  • 20

6 Answers6

60

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

user=> (int (Math/floor (/ 3 2)))
1
user=> (int (Math/ceil (/ 3 2)))
2
cfrick
  • 35,203
  • 6
  • 56
  • 68
36

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
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
10

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

1

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))])
Reb.Cabin
  • 5,426
  • 3
  • 35
  • 64
1

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
erdos
  • 3,135
  • 2
  • 16
  • 27
1

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:

N. Syiemlieh
  • 11
  • 1
  • 2
  • Note that this answer is related to a question at https://stackoverflow.com/q/10751638/1455243. The answers describe other methods. – Mars Jan 22 '23 at 05:45