How to round up a number if it's not an integer?

nick shmick picture nick shmick · Aug 30, 2015 · Viewed 26.8k times · Source

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.

Answer

Peter Neyens picture Peter Neyens · Aug 30, 2015

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