float_to_list(X)

2QdxY4RzWzUUiLuE@REDACTED 2QdxY4RzWzUUiLuE@REDACTED
Wed May 5 18:20:01 CEST 2021


On 2021-05-05 at 17:20:15 +0200,
Themba Jonga <themba.jonga@REDACTED> wrote:

> Hi All
> 
> I have the following situation which I am trying to understand (screenshot
> below) ;
> 
>    - The float N has a number of digits after the decimal point. However
>    when converted to a list N's value is reduced, albeit by a miniscule amount.
>    - The contrary is true for the float P which has its' value increased,
>    also by a tiny amount.
> 
> Is there any way to obtain a float_to_list() result which is the exact same
> as the original float, where the float variable has an arbitrary number of
> decimal places?

In short, no.  Floating point numbers in computers are inexact, and
nearly all computations (including transformations to and from decimal
notation) involve rounding errors.  As an example, how would you (the
person) write the decimal form of 1/3?  Remember, computers don't have
an infinite amount of storage for all those threes, but when you
translate any finite number of threes back to a floating point number,
you'll never quite get 1/3.  Yes, people can use math tricks to avoid
the problem; equivalent computer and Erlang tricks depend on what,
exactly, you're trying to do.

Much computer science is devoted to this topic; search engines are your
friend, now that you know what you're looking for.

> [image: image.png]

For short excerpts from a shell, go ahead and copy/paste the actual
text.  That way, if necessary, "we" can copy/paste it into our shell
instead of risking errors by having to retype it.

> I am teaching myself Erlang. However I have no formal coding training
> and I come from an accounting background.

For accounting purposes, you may find that using integers (which are
exact) representing pennies (or your smallest unit of currency) work
better than floating point numbers.  When it comes time to display them
to a user, then you can insert the appropriate decimal point or comma.


More information about the erlang-questions mailing list