Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
Carlos Nunes Avatar asked Feb 16 '15 21:02

Carlos Nunes


People also ask

How do you round in Clojure?

Math/round is the next step up in rounding technology. As with many other primitive manipulation functions in Clojure, the language prefers not to reinvent the wheel. Math/round is a Java function that rounds by adding 1/2 to a number before dropping decimal places similarly to int.

How do you round a number correctly?

Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up. And if it is followed by 0, 1, 2, 3, 4 round the number down.

Which method rounds a number up to its nearest integer?

round() method rounds a number to the nearest integer.


1 Answers

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

user=> (int (Math/floor (/ 3 2))) 1 user=> (int (Math/ceil (/ 3 2))) 2 
like image 99
cfrick Avatar answered Sep 21 '22 19:09

cfrick