Search code examples
serializationluanumberstostringnumber-formatting

How to convert a double to a small string representation without data loss in any lua without external libs?


I'd like to convert a number to a string using only any Lua version, so that

  • there is no data loss (necessary!)

  • the string representation is as small as possible (8 bytes would be fine) (optional, not necessary)
  • no external libs are used (necessary!)

  • the conversion is as fast as possible (optional, not necessary)

I don't care about

  • human readability
  • avoiding special characters

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

Solution

  •    -- 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)()