Scala math.ceil
Scala math.ceil returns the smallest integer-valued Double at least as large as its argument.
A simple example
math.ceil
- Start with 2.3
- Do this Round upward to a whole number
- Result 3
object Lesson extends App {
println(math.ceil(2.3))
}
3.0
Syntax
math.ceil(value)
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Compute the number of pages for a batch
A batch of items must be divided into pages, containers or work units of fixed size. Account for the final partial group so the last few items are neither lost nor counted as a full batch incorrectly.
object Lesson {
def main(args: Array[String]): Unit = {
for (records <- List(0, 10, 11)) {
println(math.ceil(records.toDouble / 10))
}
}
}
0.0 1.0 2.0
Convert to Double before division. Integer division would discard the partial page before ceil receives it. Zero and exact multiples need no extra rounding.
Scala documentation for math.ceil
Book enough minibuses for a field trip
A teacher has 73 passengers on the museum trip, including the adults. Each minibus seats 24. She needs enough vehicles for the last passenger as well as the first 72.
object Lesson {
def main(args: Array[String]): Unit = {
val passengers = 73
val seats = 24
val buses = math.ceil(passengers / seats.toDouble).toInt
println((buses).toString() + " minibuses")
}
}
4 minibuses
Three minibuses seat 72 people. Dividing before rounding up reserves the fourth vehicle for the remaining passenger.
Pack badges for two classrooms
A teacher has 31 badges and uses trays that hold eight each. All badges must travel, including those in a partially filled tray.
Three trays carry 24 badges. The remaining seven need the fourth tray.