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

You can also use to_string for this purpose:

iex(1)> to_string(3)
"3"
iex(2)> to_string(3.14)
"3.14"

Or string interpolation:

iex(3)> "#{3.14}"
"3.14"
iex(4)> "#{3}"
"3"

If you really want a function that converts only numbers, and raises if anything else is given, you can define your own:

defmodule Test do
  def number_to_binary(x) when is_number(x), do: to_string(x)
end

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

  • http://elixir-lang.org/docs/stable/Kernel.html#integer_to_binary/1
  • http://elixir-lang.org/docs/stable/Kernel.html#float_to_binary/1

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