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: <>
>> 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

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

Comparing this to Python 3.1:

>>> 0.34
>>> 34/100

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

>>> 0.1 + 0.2 + 0.3

But Lua's behavior is somewhat questionable:

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

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).