18

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.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
nick shmick
  • 905
  • 1
  • 9
  • 25

3 Answers3

41

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
Peter Neyens
  • 9,770
  • 27
  • 33
0

The ceil function is also directly accessible on the Double:

3.7.ceil.toInt // 4
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
-1

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)

olisteadman
  • 442
  • 6
  • 12