Converting Long Color3 Values to RGB Values

I have a system to save player builds, and the way it works is by saving a json string that includes every block’s position, rotation, and color.

Currently it saves the color in a Color3 value which has a ridiculous amount of decimals behind it. This is kind of a problem because if you were to make something massive with the system, the string that it saves can be so long that the developer console won’t even display the whole thing. Just by placing down about 130 blocks, it’s more than halfway to the data limit.

What I’m trying to do here is to change that serialized Color3 value into a serialized rgb value with only 9 digets.

Here’s the string for just ONE block placed in game.

``````-- I used this code to change the color3 value into a table that can be turned into json to be stored.
cell.Color = {color.R, color.G, color.B}

-- Then I would use this line of code in the load script to change the color of the loaded block to what was stored
clone.Color = Color3.new(c.Color[1], c.Color[2], c.Color[3])
``````

Even though I used color.R, color.G, and color.B it still returned color3 decimals.

Do you know how I could fix this and store rgb values instead?

1 Like

if you want to convert Color3.new() to Color3.fromRGB() you can multiply each value by 255

0.5, 0.5, 0.5 would be 127.5, 127.5, 127.5

if you want to limit decimals you can do this

``````math.floor(0.5 * 255 * 10^2) / 10^2
``````

since it would be RGB it’s value won’t change much while doing this
change the `2`’s to how many decimals you want
0.5 is obviously the value you had before

hope this helps

2 Likes

Additional to scaling the floating-point 0.0-1.0 value into an integer 0-255 value (where I would use `math.ceil(v * 255)` instead of `math.floor`), you could store the values as hexadecimal, which would always only be 6 characters:

``````local hexRGB = string.format(
"%02X%02X%02X",
math.ceil(color.R * 255),
math.ceil(color.G * 255),
math.ceil(color.B * 255)
)
print(hexRGB)

-- From hexadecimal back to integer base-10
local r = tonumber( "0x" .. hexRGB:sub(1,2) )
local g = tonumber( "0x" .. hexRGB:sub(3,4) )
local b = tonumber( "0x" .. hexRGB:sub(5,6) )
print(r, g, b)
``````

Though converting back from integer to floating-point will cause slight variations in the decimals, compared to the original value. However this shouldn’t be a problem, when only using them to create a color.

``````-- Floating-point to integer
local r,g,b = 0.25, 0.50, 1.00
print(math.ceil(r*255), math.ceil(g*255), math.ceil(b*255))
-- Output:  64  128  255

-- Integer to floating-point
local r,g,b = 64, 128, 255
print(r/255, g/255, b/255)
-- Output:  0.25098039215686  0.50196078431373  1.0
``````
1 Like