Page 1 of 1

Precision issue when saving integers in tables to JSON

Posted: Tue Oct 26, 2021 3:29 pm
by jPV
When I save tables with integer values as JSON with WriteTable() or SavePrefs(), some of the integer values are written as floats like 11.99999999999999 in the file.

After reading these back as Hollywood tables, the values seem to be like integers if you print them, but if you try to use them as table indexes or something like that, they don't work... they are probably floats now?

Is there something that should be fixed in Hollywood or should I just know what data I write and always do Round() conversion for values that should be integers?

This is only an issue with the new JSON format, but it's not a problem with the legacy serializer.

Code: Select all

mytable = {a=11, b=12, c=13, d=14, e=15}

secondtable = {}
For Local i=11 To 15
    secondtable[i] = "test" .. i
Next

OpenFile(1, "ram:table.json", #MODE_WRITE)
WriteTable(1, mytable, {Adapter = "default"})
CloseFile(1)

/*

After writing mytable, file contents look like this:

{
	"a": 11,
	"c": 13,
	"b": 11.99999999999999,
	"e": 15,
	"d": 13.99999999999999
}

Why some values have been written as floats?

*/

OpenFile(1, "ram:table.json", #MODE_READ)
newtable = ReadTable(1, {Adapter = "default"})
CloseFile(1)

a, b = NextItem(newtable)
While GetType(a) <> #NIL
  DebugPrint("Getting item:", b) ; Here all numbers look like integers...
  DebugPrint("Item content:", secondtable[b]) ; But the ones that were saved as floats fail here as table fields.
  a, b = NextItem(newtable, a)
Wend

/*

Output looks like this:

Getting item: 11
Item content: test11
Getting item: 13
Item content: test13
Getting item: 12
jsontest.hws:35: Table field 12 was not initialized!

*/

Re: Precision issue when saving integers in tables to JSON

Posted: Thu Oct 28, 2021 11:19 pm
by airsoftsoftwair
What platform is this?

Re: Precision issue when saving integers in tables to JSON

Posted: Fri Oct 29, 2021 7:02 am
by jPV
On MorphOS... doesn't seem to happen on Windows and haven't tried on other platforms.

Re: Precision issue when saving integers in tables to JSON

Posted: Fri Oct 29, 2021 9:56 pm
by airsoftsoftwair

Code: Select all

- Fix: When using the new JSON serializer, integers were often serialized as doubles on some platforms (MorphOS, AmigaOS 4, maybe more)