Numbers & Math
7 min · Scala
Do math with variables and the basic operators.
Enemy 1 of 5
The four basic operators
Scala has several numeric types — `Int` for whole numbers, `Double` for decimals, `Long` for very large whole numbers, and more — but for everyday arithmetic you rarely need to think about which one you have. Write `val price = 5` and Scala infers `Int`; write `val price = 5.0` and it infers `Double`. Mixing an `Int` and a `Double` in one expression automatically promotes the result to `Double`, so `5 / 2.0` gives `2.5` rather than truncating.
One gotcha worth knowing up front: dividing two `Int` values with `/` performs integer division, discarding any remainder. `7 / 2` is `3`, not `3.5`. If you want the fractional part, at least one side needs to be a `Double` — `7.0 / 2` gives `3.5`.
The familiar arithmetic operators are `+` (add), `-` (subtract), `*` (multiply), and `/` (divide). They follow standard order of operations (multiplication and division before addition and subtraction), and you can force a different order with parentheses, exactly like in ordinary math notation.
A common pattern is to store the pieces of a calculation as named values first, and then combine them inside `println` — this keeps the arithmetic itself readable, since each name explains what that number means, and you can reuse the values elsewhere in the program without retyping them.
Loading editor...