Search code examples
erlangelixir

Float to string without scientific notation?


Is there a good way to convert floats to strings in Erlang/Elixir, without scientific notation, and without specifying how many decimal digits I want?

Neither of these do what I need.

:erlang.float_to_binary(decimals: 10): gives trailing zero decimals
float_to_binary(100000000000.0, [short]).: prints scientific notation


Solution

  • You can provide the compact option to trim trailing zeros:

    iex> :erlang.float_to_binary(100000000000.0, [:compact, decimals: 20])
    "100000000000.0"
    

    Note however that floats cannot be accurately represented as decimals, so you may end up with unexpected results. For example:

    iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 10])
    "0.3"
    iex> :erlang.float_to_binary(0.1 + 0.2, [:compact, decimals: 20])
    "0.30000000000000004441"