Scala — Values and integer arithmetic
Scala val binds a name once. With nonnegative Int amounts, dividing by 100 gives whole dollars and the remainder operator gives the cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
object Lesson extends App {
var n = 2
n += 1
println(n)
}
3
Calculate a receipt in cents
val establishes an immutable binding. Both operands are Int in the division, so the quotient drops the fractional part. The format call pads the remainder to two digits.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
val priceCents = 125
val quantity = 3
val total = priceCents * quantity + 50
println("%d.%02d".format(total / 100, total % 100))
}
}
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.