How to get the ordinary decimal notation of a float

iex> 75000 / 12.5
6.0e3

iex(14)> 75000 / 12.5 |> Float.to_string                      
"6.0e3"

It is kind of weird that Elixir is formatting such a small number using the scientific notation. Is there a way around to display and/or convert to string the float and get 6000.0 and not 6.0e3?

Cheers

iex> 75000/12.5 |> :erlang.float_to_binary([ decimals: 2]) 
"6000.00"

or

iex> 75000/12.5 |> :erlang.float_to_binary([:compact, decimals: 2])
"6000.0"
2 Likes

The documentation for Float.to_string/1 says

It uses the shortest representation

so I guess that’s why it chooses "6.0e3" over 6000.0, the latter is one character longer.

Take a look at :erlang.float_to_binary/2, here’s how it can be used:

iex(18)> max_precision = 6
6
iex(19)> :erlang.float_to_binary(6000.0, [:compact, decimals: max_precision])
"6000.0"
3 Likes

Thank you so much for your answer @alco !

I missed that one. Thank you for pointing at it.

Thank you @outlog and @alco for your answers.
Unfortunately it is not easy to do this within Elixir itself.
Now I see that Float.to_string/2 had been deprecated and it accepts the same options as :erlang.float_to_binary/2

1 Like