Hanging Decimals with JSON Encoding

Hey everyone,

I’ve been working on better ways to compress and serialize my data to use in DataStores. I’ve got data to be pretty small so far. I used to use GUIDs but opted for a truncated tick() for the ID. I do this because it’s impossible for a player to place an object faster than 1 millisecond.

My issue is the truncation. I can successfully truncate that value properly and get an output however that changes when I serialize with JSON.

Here is my rounding function:

function round(x, n)
    n = math.pow(10, n or 0)
    x = x * n
    if x >= 0 then x = math.floor(x + 0.5) else x = math.ceil(x - 0.5) end
    return x / n
end

I am able to get outputs such as this:

  1587493138.053

However, when serialized into JSON strings I get this:

 {"N":"LongHallwayWindow3","E":[],"D":["Level1","Structure"],"Id":1587493138.05299997329711914063,"P":{"Z":-92,"R":180,"X":-120,"Y":6.5}}

(Keep in mind the above is serialized further in regards to the Directory Names and the Object Names.)

Perhaps this could be inconsistencies in JSON? If it’s not fixable is there any way I could still accomplish this?

1 Like

I found that converting it into a string before putting it through JSON takes care of this issue. Only two additional characters.

1 Like

you could do:

for positive numbers:
math.floor(x100)/100
and negative numbers
math.floor(x
-100)/-100

note that the amount of 0’s following the 1 will be your decimal places.

1 Like

another approach might be using string manipulation

– Add decimal with precision of 2 for a currency output
local str = “$%.2f”
print(string.format(str, 300))

1 Like