I'd like to convert a number to a string using only any Lua version, so that
I don't care about
I tried the built-in tonumber
function, but it does not always give correct results:
> print((2+256^6)==(1+256^6))
false
> print(tostring(2+256^6)==tostring(1+256^6))
true
-- Encoding/decoding without data loss
local NaN_serialized = {
[string.format('%.17g', 1/0 )] = '1/0',
[string.format('%.17g', -1/0 )] = '-1/0',
[string.format('%.17g', 0/0 )] = '0/0',
[string.format('%.17g', -(0/0))] = '-(0/0)'
}
-- How to encode:
str_value = string.format('%.17g', num_value):gsub('^.*', NaN_serialized):gsub(',', '.')
-- How_to_decode:
num_value = loadstring("return "..str_value)()