Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Stratus3D Avatar asked Nov 04 '13 14:11

Stratus3D


People also ask

How do you convert float to int in Elixir?

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.

What are binaries in Elixir?

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.


2 Answers

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
like image 180
sasajuric Avatar answered Nov 10 '22 20:11

sasajuric


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
like image 31
Ramon Snir Avatar answered Nov 10 '22 18:11

Ramon Snir