I want to calculate a simple number, and if the number is not an integer I want to round it up.
For instance, if after a calculation I get 1.2
, I want to change it to 2
. If the number is 3.7
, I want to change it to 4
and so on.
I want to calculate a simple number, and if the number is not an integer I want to round it up.
For instance, if after a calculation I get 1.2
, I want to change it to 2
. If the number is 3.7
, I want to change it to 4
and so on.
You can use math.ceil
to round a Double
up and toInt
to convert the Double
to an Int
.
def roundUp(d: Double) = math.ceil(d).toInt
roundUp(1.2) // Int = 2
roundUp(3.7) // Int = 4
roundUp(5) // Int = 5
The ceil
function is also directly accessible on the Double
:
3.7.ceil.toInt // 4
Having first imported math
import scala.math._
(the final dot & underscore are crucial for what comes next)
you can simply write
ceil(1.2)
floor(3.7)
plus a bunch of other useful math functions like
exp(1)
pow(2,2)
sqrt(pow(2,2)