Arithmetic Operators
In this page:
Arithmetic Operators
Scala provides +, -, *, /, and % for arithmetic, all implemented as methods on numeric types (Scala has no truly special-cased operators). Integer division truncates any fractional part, while dividing two Doubles keeps precision. % returns the remainder of a division.
Warning: Dividing two Ints, like 7 / 2, gives 3, not 3.5 -- make at least one operand a Double to get a fractional result.
Example: Arithmetic Operators
object Main extends App {
val a = 7
val b = 2
println(a + b)
println(a - b)
println(a * b)
println(a / b) // integer division
println(a % b) // remainder
println(a.toDouble / b) // fractional division
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: