Numbers
Integers
Plain digits build an integer of any size, limited only by memory. The arithmetic operators are the usual four.
erl
1> 42.
42
2> 2 + 3 * 4.
14
Floats
A dot builds a float. The division operator always returns a float, even when both sides divide cleanly.
Use the caret for powers and the math module for the rest of the school functions.
erl
1> 3.14.
3.14
2> 7 / 2.
3.5
3> 2.0 * 2.0.
4.0
Integer math
The div operator divides whole numbers, and rem gives the remainder. Both demand integer arguments.
The result sign follows the dividend, so negative numbers keep the remainder sign of the left side.
erl
1> 7 div 2.
3
2> 7 rem 2.
1
3> -7 rem 2.
-1
Other bases and chars
A base prefix builds a number in that base: two hashes for binary, sixteen for hexadecimal. The dollar sign builds a character code.
These literals are plain integers once compiled, so they mix freely with the rest of your math.
erl
1> 2#1010.
10
2> 16#ff.
255
3> $A.
65
Next: Atoms
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How large can an Erlang integer be?
Answer
Any size that fits in memory
Erlang integers are arbitrary precision: the runtime grows the number as needed.
-
What does
2 + 3 * 4.return?Answer
14Multiplication binds tighter than addition, so the shell computes 3 * 4 first and adds 2.
-
What does
7 / 2.return?Answer
3.5The slash always divides as a float, even when both arguments are integers.
-
Which operator divides integers and drops the remainder?
Answer
divdivis integer division;remgives the remainder instead. -
What does
7 div 2.return?Answer
3divkeeps the whole part of the division, so 7 divided by 2 is 3. -
What does
7 rem 2.return?Answer
1Seven divided by two leaves a remainder of one.
-
What does
-7 rem 2.return?Answer
-1The remainder takes the sign of the dividend, so a negative left side gives a negative remainder.
-
What does
2#1010.build?Answer
The number
10The prefix
2#reads the digits as binary, and 1010 in binary is ten. -
What does
16#ff.return?Answer
25516#marks a hexadecimal literal, and ff is 255 in decimal. -
What does
$A.return?Answer
The number
65The dollar sign builds the character code of the next character, and the code of A is 65.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev