Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Convert float to string

Tags:

elixir

I am trying to figure out how to convert a float to a string/binary but seems like its not as easy as it looks

iex(1)> to_string(1200.00)
"1.2e3"

iex(2)> Float.to_string(1200.00)
"1.2e3"

We need "1200.00" to come out...just not in the exponent notation

like image 230
sat Avatar asked Aug 03 '16 03:08

sat


1 Answers

Without further details about your usecase, this will give you your desired result:

iex(1)> Float.to_string(1200.00, decimals: 2)
"1200.00"

It is using erlang's float_to_binary/2 and will be deprecated in elixir 1.4 (https://github.com/elixir-lang/elixir/blob/v1.3.2/lib/elixir/lib/float.ex#L225):

def to_string(float, options) do
    :erlang.float_to_binary(float, expand_compact(options))
end

In elixir 1.8, there still is Float.to_string/1. Float.to_string/2 is deprecated and the suggestion is to use :erlang.float_to_binary/2 directly.

like image 148
splatte Avatar answered Sep 18 '22 16:09

splatte