🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Arithmetic Operators

Arithmetic operators are symbols that do maths on numbers. Elixir uses familiar signs for basic maths and named functions for whole-number division.

Add, subtract and multiply

The basic operators work on integers and floats. Each line below prints one result.

IO.puts(4 + 5)
IO.puts(10 - 3)
IO.puts(3 * 6)

Slash always returns a float

The slash divides and always gives a float. Even a clean division keeps the decimal point.

IO.puts(7 / 2)
IO.puts(6 / 2)

Powers keep the type of the numbers

The ** operator raises a number to a power. Two integers give an integer, and a float in the power gives a float.

IO.puts(2 ** 10)
IO.puts(2.0 ** 3)
IO.puts(Integer.pow(3, 3))

Example

price = 17
quantity = 3
total = price * quantity
share = div(total, 4)
leftover = rem(total, 4)
gap = abs(40 - total)
IO.puts(total)
IO.puts(share)
IO.puts(leftover)
IO.puts(gap)
IO.puts(max(total, 40))
IO.puts(min(total, 40))

Key points

  • Basic operators: + adds, - subtracts, and * multiplies numbers.
  • Float division: / always returns a float, so 6 / 2 gives 3.0.
  • Whole division: div(7, 2) returns the whole part 3.
  • Remainder: rem(7, 2) returns the leftover value 1.
  • Powers: ** between two integers returns an integer, and Integer.pow always returns an integer.
  • Helpers: abs gives a number's positive size, and max and min pick the larger or smaller of two values.

In this example, price times quantity gives a total of 51. div and rem split that total into shares of 12 with 3 left over, abs turns the gap from 40 into the positive size 11, and max and min compare the total with 40.

Note

Elixir integers can grow as large as the maths needs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does div(9, 4) return?