Reputation: 4906
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.
Upvotes: 6
Views: 4481
Reputation: 6059
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
Upvotes: 21
Reputation: 7560
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
Upvotes: 2
Reputation: 14042
inspect does this
iex(1)> inspect(3)
"3"
iex(2)> inspect(3.14)
"3.14"
iex(3)> a = inspect(3.14)
"3.14"
iex(4)> a
"3.14"
Upvotes: 1