How to Fix a Floating-Point Error Arithmetic?

So I’m making a game that involves the simple concept of working for gold.
I have stamina at 0 because right now I’m focused on the math rather than on the rest of implementation, nothing currently rides on the value of stamina right now.
So if I click a button to work, I use 0.2 stamina. Clicking the button will add -0.2 to my stamina (0), then override the stored value of stamina (-0.2).

The issue occurs during the process of stamina = (current)stamina + adjustment
With the values plugged in, it’s a simple stamina = 0 - 0.2
However, rather than getting -0.2, I will get either -0.19999999999 or I’ll get -0.200000000001.

I figured I could fix this by storing a backup and just redo it until it’s correct.
So my loop is
while stamina ~= backup + adjustment do
stamina = backup + adjustment
end

it’ll get it the first time, I’ll get my -0.2
Then I’m stuck in an accidentally infinite loop of
while stamina ~= -0.2 - 0.2 do
stamina = -0.2 - 0.2
end

that shouldn’t be infinite by any means, but roblox has proven consistent with being unable to properly handle adding or subtracting decimals to as far as the tenths place, resulting in my loop just going on forever.

If roblox apparently reaches a point of being unable to add or subtract, is there a fix I can utilize or a means of flushing the arithmetic system in-game so it can reset and try again when it hits this wall?

You can’t, instead just check if the value is close enough to the desired value.

local function isValueClose(value1, value2, power)
	if math.round(value1 * 10 ^ power)/10 ^ power == value2 then
		return true
	else
		return false
	end
end

power should be any positive integer, where larger integers require value1 to be closer to value2 for the function to return true.

1 Like

That’s unfortunate. Oh well. I appreciate the recommended course of action. Thank you!

2 Likes