Arithmetic Operators
Arithmetic operators are the calculator buttons: add, subtract, multiply, divide, and find the remainder. Scala uses them to do math with numbers and variables.
In this page:
Syntax
a + b
a - b
a * b
a / b
a % b
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
/on twoIntvalues and expecting a decimal, when7 / 2is3; use7.0 / 2. - Dividing an
Intby0, which throws anArithmeticException, while aDoublegivesInfinity. - Using
^for exponents, when it is bitwise XOR and you needmath.pow(a, b).
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: