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.

  1. 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.

  2. What does 2 + 3 * 4. return?

    Answer

    14

    Multiplication binds tighter than addition, so the shell computes 3 * 4 first and adds 2.

  3. What does 7 / 2. return?

    Answer

    3.5

    The slash always divides as a float, even when both arguments are integers.

  4. Which operator divides integers and drops the remainder?

    Answer

    div

    div is integer division; rem gives the remainder instead.

  5. What does 7 div 2. return?

    Answer

    3

    div keeps the whole part of the division, so 7 divided by 2 is 3.

  6. What does 7 rem 2. return?

    Answer

    1

    Seven divided by two leaves a remainder of one.

  7. What does -7 rem 2. return?

    Answer

    -1

    The remainder takes the sign of the dividend, so a negative left side gives a negative remainder.

  8. What does 2#1010. build?

    Answer

    The number 10

    The prefix 2# reads the digits as binary, and 1010 in binary is ten.

  9. What does 16#ff. return?

    Answer

    255

    16# marks a hexadecimal literal, and ff is 255 in decimal.

  10. What does $A. return?

    Answer

    The number 65

    The 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

Banner image