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
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.
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