float_to_list vs io:format ~w

zxq9 zxq9@REDACTED
Mon Jun 28 11:31:44 CEST 2021

Floats are white lies but useful engineering approximations and reals 
are a fake contrivance that imagines the universe to be infinitely smooth.

I'm being silly above (but seriously, reals are fake), but the bottom 
line is it really isn't a simple thing to pick a "right" representation 
and I imagine the difference comes down to use case: formatting data for 
humans VS exporting data to other machines.

"Practically speaking, the user intends 10.2 to be 10.2 even though that 
is an impossible number to represent as a float."

"The closest string representation of this value is literally X so it 
will be represented in full."

My question is: What is the algorithm for the 10.2 -> "10.2" 
representation? Is there some rounding rule? This is probably all 
covered in some part of IEEE 754 I've never gotten around to reading.


On 2021/06/28 18:23, Viktor Söderqvist wrote:
> Hi!
> Apparently, float_to_binary/1 and float_to_list/1 return a different 
> textual representation than io:format("~w", [Float]) and the shell.
>      Eshell V11.1.8  (abort with ^G)
>      1> float_to_list(10.2).
>      "1.01999999999999992895e+01"
>      2> 1.01999999999999992895e+01.
>      10.2
>      3> io:format("~w~n", [10.2]).
>      10.2
>      ok
>      4> 1.01999999999999992895e+01 =:= 10.2.
>      true
> Apparently, both are correct textual representations of the same 
> floating point value. Why don't they use the same algorithm?
> Viktor

More information about the erlang-questions mailing list