Precision issue when saving integers in tables to JSON

Report any Hollywood bugs here
Post Reply
User avatar
jPV
Posts: 600
Joined: Sat Mar 26, 2016 10:44 am
Location: RNO
Contact:

Precision issue when saving integers in tables to JSON

Post 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!

*/
User avatar
airsoftsoftwair
Posts: 5425
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

Re: Precision issue when saving integers in tables to JSON

Post by airsoftsoftwair »

What platform is this?
User avatar
jPV
Posts: 600
Joined: Sat Mar 26, 2016 10:44 am
Location: RNO
Contact:

Re: Precision issue when saving integers in tables to JSON

Post by jPV »

On MorphOS... doesn't seem to happen on Windows and haven't tried on other platforms.
User avatar
airsoftsoftwair
Posts: 5425
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

Re: Precision issue when saving integers in tables to JSON

Post 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)
Post Reply