Numbers

Numbers in Elixir are integers and floats, and the two are separate types with separate rules. An integer never overflows and never loses a digit; a float follows the 64-bit IEEE 754 format and carries the small surprises of every language that uses it. The arithmetic operators are the ones you expect, and the choice between /, div and rem is the part a reader has to learn.

Integers of any size

An integer is as large as the memory allows. There is no 32-bit or 64-bit limit, so a factorial or a timestamp multiplication keeps every digit instead of wrapping around. Underscores may group digits for the reader and change nothing about the value:

integers.exs

seconds = 86_400 IO.puts(seconds * 365) IO.puts(2 ** 100) IO.puts(123_456_789 * 1_000)

elixir integers.exs

31536000
1267650600228229401496703205376
123456789000

The second line is 2 to the power of 100, a number that does not fit in 64 bits, printed in full. The exponent operator is **, and it returns an integer when both sides are integers. Large arithmetic is slower than small arithmetic, but it is never wrong.

The slash and div rem

The slash always returns a float, even when the division comes out even. Integer division and the remainder are separate functions, div/2 and rem/2, and the identity div(a, b) * b + rem(a, b) == a holds for every pair. The script prints all four results:

division.exs

IO.puts(7 / 2) IO.puts(4 / 2) IO.puts(div(7, 2)) IO.puts(rem(7, 2)) IO.puts(div(7, 3) * 3 + rem(7, 3))

elixir division.exs

3.5
2.0
3
1
7

4 / 2 is 2.0 and not 2: the slash made a float, and a float prints its point. A program that needs an integer count calls div/2; a program that needs a fraction calls / and lives with a float.

Floats and their rounding

A float is a 64-bit double, and most decimal fractions have no exact binary form. Adding 0.1 and 0.2 gives a number a hair above 0.3, which is what the first line below shows. The rounding functions are how a program keeps the digits a reader wants: round/1 goes to the nearest integer, trunc/1 drops the fraction, and Float.round/2 keeps a number of decimal places:

floats.exs

IO.puts(0.1 + 0.2) IO.puts(Float.round(3.14159, 2)) IO.puts(round(3.7)) IO.puts(trunc(3.7))

elixir floats.exs

0.30000000000000004
3.14
4
3

The artifact is not a bug of Elixir: the same sum gives the same digits in any language that uses IEEE doubles. Compare floats with a tolerance, or keep money in integer cents, and the surprise disappears. The values lesson showed that 3.0 keeps its point when printed; that is the same rule seen from the other side.

Convert between numbers and text

A number and its text are different values, and the conversion is explicit. Integer.to_string/1 writes an integer, String.to_integer/1 reads one back, and the parse functions read as much as they can and return the rest of the text with the value:

convert.exs

IO.puts(Integer.to_string(42)) IO.puts(String.to_integer("42")) IO.inspect(Integer.parse("42abc")) IO.inspect(Float.parse("3.14"))

elixir convert.exs

42
42
{42, "abc"}
{3.14, ""}

Integer.parse/1 returns a tuple of the number and the text it could not read, which is how a parser walks a line of input. String.to_integer/1 is the strict version: the whole binary has to be a number, or the call raises.

The mistake: parsing a float as an integer

String.to_integer/1 accepts digits and an optional sign, and nothing else. A decimal point makes the binary a float, so the strict call stops the program with an ArgumentError instead of returning 3:

parse.exs

IO.puts(String.to_integer("3.5"))

elixir parse.exs

** (ArgumentError) errors were found at the given arguments:

* 1st argument: not a textual representation of an integer

:erlang.binary_to_integer("3.5")
parse.exs:1: (file)

The message says which argument was wrong and why. For text that may hold either kind of number, Integer.parse/1 and Float.parse/1 are the tools: they return a tuple, so the caller decides what to do with text that is not a number. The chapter on errors comes back to the difference between a call that raises and one that returns a tuple.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the largest integer Elixir can hold?

    Answer

    There is no fixed limit; it grows with the memory available

    Integers are arbitrary precision, so a value never overflows into a wrapped number.

  2. What does 7 / 2 return?

    Answer

    3.5, a float

    The slash always returns a float; div/2 is the integer division.

  3. What does div(7, 2) return?

    Answer

    3

    div/2 drops the fraction and returns an integer.

  4. Why does 0.1 + 0.2 print 0.30000000000000004?

    Answer

    A float is a binary fraction, and 0.1 has no exact binary form

    IEEE 754 doubles cannot represent every decimal fraction exactly, so the sum is a hair high.

  5. What does this program print? IO.puts(div(7, 2))

    Answer

    3

    div/2 returns the integer part of the quotient.

  6. What does this program print? IO.puts(rem(7, 2))

    Answer

    1

    rem/2 returns the remainder of the integer division.

  7. What does this program print? IO.puts(2 ** 10)

    Answer

    1024

    The exponent operator with two integers returns 2 multiplied by itself ten times.

  8. What does this program print? IO.puts(4 / 2)

    Answer

    2.0

    The slash returns a float even when the division is exact.

  9. What does this program do? IO.puts(div(1, 0))

    Answer

    An ArithmeticError, because an integer cannot be divided by zero

    Integer division by zero raises ArithmeticError; floats have their own infinity value.

  10. What does this program do? IO.puts(String.to_integer("3.5"))

    Answer

    An ArgumentError, because the text is not an integer

    String.to_integer/1 is strict: a decimal point is not part of an integer literal.

Автор статьи: Arthur Isaev

Изображение баннера