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.
Use trunc(2.0) or round(2.0) . Those are auto-imported since they are part of Kernel and they are also allowed in guard clauses. FWIW: round/1 still returns a Float at this point -- trunc/1 will convert to Integer.
A binary is a bitstring where the number of bits is divisible by 8. That means that every binary is a bitstring, but not every bitstring is a binary. We can use the is_bitstring/1 and is_binary/1 functions to demonstrate this.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With