typeserlangnumbersbitstringelixir

Elixir one function to convert both floats and integers to bitstrings?


Does Elixir have a function that accepts integers and floats and converts them to strings?

I need something like this:

a = 3
b = 3.14
number_to_binary(a)
% => "3"
number_to_binary(b)
% => "3.14"

Is there a function in Elixir that already does something like this? I looked at the docs and didn't see anything. I also checked the Erlang docs and didn't see any functions like this either.


Solution

  • For each one of the types, there is a function:

    If you want a general number_to_binary function, try simply using inspect (that is Kernel.inspect, not IO.inspect).

    a = 3
    b = 3.14
    inspect a
    % => "3"
    inspect b