Numbers and arithmetic
As you could see, numbers in Elixir are either integers or floats. You can use is_integer/1 and is_float/1 to check what a value is.
Check if a value is an integer:
# 💡 Try changing to `is_float`.
is_integer(123)
Check if a value is a float:
# 💡 Try changing to `is_number`.
is_float(4.5)
Elixir allows expressing numbers in decimal, binary, octal, hexadecimal and exponential notation.
Decimal notation:
123
Binary notation:
0b1010
Octal notation:
0o777
Hexadecimal notation:
0x1F
Float in decimal notation:
1.0
Exponential notation:
1.0e-10
Normally, integers can be arbitrarily big and they never overflow (or underflow). However, the AtomVM runtime which we’re using in the browser only supports integers up to 64 bits and overflow raises an error. Floats are always stored on 64 bits and overflow raises an error.
Now that we understand number types, let’s explore arithmetic operations.
Basic Arithmetic
Let’s explore basic arithmetic operations.
Addition:
1 + 2
Multiplication:
5 * 6
Division:
10 / 2
Notice, that 10 / 2 returned 5.0. Division in Elixir always returns a float. For integer division, use div/2:
div(10, 2)
Remainder of integer division:
rem(10, 3)
For float to integer conversion, you can use round/1 or trunc/1:
round(3.58)
# 💡 Try changing to `ceil`. How does the result change?
trunc(3.58)