All lessons

Numbers & Math

6 min · Elixir

Do math with variables and the basic operators.

Elixir · Numbers & Math0/5 cleared

Enemy 1 of 5

The basic operators

Whole numbers are integers and numbers with a decimal point are floats. The / operator always gives a float, so 10 / 2 is 5.0. Use div for whole-number division.

This code stores a price and a quantity in named variables, multiplies them, and prints the result with IO.puts. Press Run and look for 15 in the output.

Why this works

Elixir has two everyday numeric types: integers (whole numbers, with no fixed size limit: Elixir integers can grow arbitrarily large without overflowing) and floats (decimal numbers). Elixir figures out which one you mean from how you write the literal: `5` is an integer, `5.0` is a float. Mixing the two in an expression, like `5 + 2.5`, produces a float.

One thing to watch for: `/` always produces a float in Elixir, even when dividing two integers evenly: `10 / 2` gives `5.0`, not `5`. If you specifically want integer division that drops the remainder, use `div/2` (`div(10, 2)` gives `5`), and `rem/2` for the remainder (`rem(10, 3)` gives `1`). This trips up people coming from languages where `/` on two integers quietly does integer division.

The four familiar operators (`+`, `-`, `*`, `/`) work as you'd expect, following standard order of operations, with parentheses available to force a different grouping. Binding the pieces of a calculation to names first, then combining them inside `IO.puts`, keeps the intent of the calculation readable: the names explain what each number represents.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.