lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


* Luiz Henrique de Figueiredo:

>> There is dtoa for this purpose, see: <http://www.netlib.org/fp/>
>> It's quite portable.
>
> And about a quarter of the size of the whole Lua source; it translates
> to about 30k of code. Plus dtoa is probably already part of libc; see
> http://lua-users.org/lists/lua-l/2002-08/msg00193.html

Correctness has its price. 8-/

>> What I would like to see is that n = tonumber(tostring(n)) holds for
>> all finite numbers, and that tostring(n) returns the shortest possible
>> representation such that n = tonumber(tostring(n)) holds.
>
> The price for this is ugly-looking strings ending with a row of nines
> or with a row of zeros followed by what looks like noise. This upsets
> (naive) users. Lua makes a point to use %.14g instead of %.17g in
> tostring. See http://lua-users.org/lists/lua-l/2004-12/msg00027.html

Comparing this to Python 3.1:

>>> 0.34
0.34
>>> 34/100
0.34

Of course, there are still corner cases which are somewhat unexpected:

>>> 0.1 + 0.2 + 0.3
0.6000000000000001

But Lua's behavior is somewhat questionable:

> x = 0.1 + 0.2 + 0.3
> = x
0.6
> = x == 0.6
false

It could be argued that tostring is lossy for tables, so it can be
lossy for numbers, too.

Unfortunately, there doesn't seem to be a good way to obtain the
Python behavior from libc (short of truncating the string character by
character and check if it's still equal when decoded as a number).