Števo Bačkor's public notes

Elixir's Integers and Floats

April 15, 2019

This is just a sum of all hexdocs examples used to convert between Elixir’s number formats back and forth.

Value parsing

Float.parse/1 and Integer.parse/1

iex> Float.parse("18.5xyz")
{18.5, "xyz"}

Wait what? How should I use this tuple? Well lets say you need to convert age in string format to number (Integer) of days from now:

age = "18.5xyz"
days =
  case Float.parse(age) do
    :error -> 0
    {float, _} -> (365 * float) |> Float.ceil() |> Kernel.trunc()
  end

# days = 6752

Note that Kernel.trunc/1 returns the integer part of a number.

The same goes with Integer.parse/1

iex> Integer.parse("18.5xyz")
{18, ".5xyz"}

Type conversion

String.to_float/1 and String.to_integer/1

Another option is using String module which has some drawbacks. String module provides only direct type converson, without error handling.

iex> String.to_float("18.5xyz")
** (ArgumentError) argument error
    :erlang.binary_to_float("18.5xyz")
iex> String.to_float("18.5")
18.5
iex> String.to_integer("18.5")
** (ArgumentError) argument error
    :erlang.binary_to_integer("18.5")
iex> String.to_integer("18")
18

Enjoy awesome Elixir!


Štefan Bačkor

Written by Štefan Bačkor who lives and works from Slovakia. You should check his Twitter or Github