Arithmetic Operators

Arithmetic operators in Elixir allow you to perform basic mathematical calculations. These operators work with numbers and support integer as well as floating-point arithmetic.

Here are the most popular arithmetic operators:

  • Addition (+): This operator adds two numbers together.

    iex> 2 + 2
    4
  • Subtraction (-): This operator subtracts the second number from the first.

    iex> 4 - 2
    2
  • Multiplication (*): This operator multiplies two numbers.

    iex> 3 * 3
    9
  • Division (/): This operator divides the first number by the second. It always returns a float.

    iex> 10 / 2
    5.0

    If you need integer division, you can use the div/2 function:

    iex> div(10, 2)
    5

These operators follow standard mathematical precedence rules. If you want to ensure a specific order of operations, use parentheses to make your intentions clear:

iex> 2 + 2 * 3
8

iex> (2 + 2) * 3
12

Elixir’s arithmetic operators are not just for integers and floats; they can also operate on other data types, such as complex numbers and matrices, provided the appropriate libraries are installed. However, the focus here is on their use with numbers.