Shorter scientific notation like "1.01e5" instead of "1.01e+05" (:erlang.float_to_binary)

Hi

I would like to know if/how I can format a float in shorter scientific notation than what :erlang.float_to_binary gives me. For example

iex(1)> 1012.670|>:erlang.float_to_binary(scientific: 2)
"1.01e+03"

But I want “1.01e3”. Is this possible? I tried to combine Float.round and Float.to_string but this does not necessarily give scientific notation. Thank you.

I don’t think that this is possible. If you check the documentation for :erlang.float_to_list/2 you can see what the options give you. An alternative could be to use Erlang formatted output but I can’t remember how the options work.

1 Like

Thank you. I will then just stick to the longer scientific notation. In case one really needs it one could just post-process the string but I think I don’t really need the shorter notation, it was just bothering me a bit.

You can do that with ex_cldr_numbers but you probably wouldn’t use it if this is the only requirement (I’m the author).

iex> Cldr.Number.to_string 1012.670, format: "0.00E+0"
{:ok, "1.01E+3"}
3 Likes

It works! The exponential “E” is always capital but that does not matter for me.