Scala Arithmetic
Arithmetic is doing math with numbers in code. Scala follows the normal order for math steps, and parentheses can change that order.
Add, subtract and multiply
Each line does one math step and prints the result. The printed numbers prove each sign did its job.
@main def main(): Unit =
println(10 + 5)
println(10 - 3)
println(4 * 3)Int division drops the decimal part
Dividing two whole numbers gives a whole number back. Dividing with a decimal number keeps the decimal part.
@main def main(): Unit =
println(7 / 2)
println(7.0 / 2)
println(7 % 2)Parentheses change the result
Multiplication runs before addition when there are no parentheses. Parentheses make the inside step run first.
@main def main(): Unit =
println(2 + 3 * 4)
println((2 + 3) * 4)Example
@main def main(): Unit =
val notebooks = 3
val priceEach = 4
val total = notebooks * priceEach
val shipping = 5
val grandTotal = total + shipping
println(grandTotal)
println(grandTotal - shipping)
println((grandTotal - shipping) / notebooks)Key points
- Addition: + adds two numbers together.
- Subtraction: - takes one number away from another.
- Multiplication: * multiplies two numbers.
- Division: / divides one number by another.
- Remainder: % gives what is left after division.
- Precedence: precedence is the order in which math steps run when no parentheses say otherwise.
In this example, notebooks times priceEach gives the total of 12. Adding shipping gives a grand total of 17, and taking shipping away gives 12 again. Dividing 12 by 3 notebooks gives 4 for each notebook.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does println(2 + 3 * 2) print?