Skip to content
AgileLogics
4 min read

Numbers and Math

Prerequisites: Data types

@main def math(): Unit =
  println(7 + 2)
  println(7 - 2)
  println(7 * 2)
  println(7 / 2)
  println(7 % 2)
  println(7.0 / 2)
  println(7 / 2.0)
  println(-7 / 2)
  println(Math.floorDiv(-7, 2))
9
5
14
3
1
3.5
3.5
-3
-4
  • Dividing two Ints gives an Int, dropping the remainder: 7 / 2 is 3. Make one side a Double for a decimal result.
  • Integer division truncates toward zero (-7 / 2 is -3); Math.floorDiv rounds down instead.
  • % gives the remainder.

The math package

import scala.math.*

@main def mathFunctions(): Unit =
  println(sqrt(16))
  println(pow(2, 10))
  println(abs(-3.5))
  println(max(4, 9))
  println(round(2.5))
  println(round(-2.5))
  println(floor(2.7))
  println(ceil(2.1))
  println(Pi)
4.0
1024.0
3.5
9
3
-2
2.0
3.0
3.141592653589793

import scala.math.* brings in every function from scala.math, so you can write sqrt instead of scala.math.sqrt. Note that round rounds halves up (towards positive infinity): 2.5 → 3, -2.5 → -2.

Money: use BigDecimal

@main def money(): Unit =
  println(0.1 + 0.2)
  println(BigDecimal("0.1") + BigDecimal("0.2"))
  val total = BigDecimal("19.99") * 3
  println(total.setScale(2, BigDecimal.RoundingMode.HALF_UP))
0.30000000000000004
0.3
59.97

Double stores approximations, so 0.1 + 0.2 isn't exactly 0.3. BigDecimal stores exact decimal values — use it for money.

Practice

A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and each share as a decimal with 2 places.

Show solution
@main def pizza(): Unit =
  val slices = 8
  val people = 3
  println(slices / people)
  println(slices % people)
  println(f"${slices.toDouble / people}%.2f")
2
2
2.67