Adding numbers to a value causes the value to become uneven

Hello,

somehow I have issues doing mathquestions in a script which aren’t supposed to be happening. I want to make sure if this is a bug or if that’s just how it is.

So I wrote a few simple lines of code just like this:

local Temperature = 3.2  

while Prompt.ActionText == "Close" do
	task.wait(5)
	Temperature += 0.05
	print(Temperature)
	Thermometer.Screen.SurfaceGui.TextLabel.Text = tostring(Temperature).."°C"
end

It is supposed to add 0.05 to 3.2 every 5 seconds. The code does it and for the first moments it seems to do it right.
image

but after the third time it suddendly begins to do this:
image

I don’t think that this is supposed to happen so I thought about writing a bug report.

floating point issue. Bug which won’t be fixed by anyone exept yourself.

As hinted at before, this is a side effect of the math computers need to do in order to store floating point numbers (AKA the thing that lets you have decimal points). You can read more here: https://0.30000000000000004.com/

In order to show your players 3.6 instead of 3.59999999…, you can change your code to:

Thermometer.Screen.SurfaceGui.TextLabel.Text = string.format("%.2f°C", Temperature)

This will display the temperature with two decimal points, rounded to the closest digit.

> =string.format("%.2f", 3.3 + 0.05)
3.35
> =string.format("%.2f", 3.3)
3.30
4 Likes

Alternatively the code could avoid working with decimal numbers altogether, which would actually eliminate the error because whole numbers are exactly represented. This would be important if you were dealing with something more sensitive like a player’s currency.

So in this example the temperature would start at 320 and increment by 5 exactly each time. Later the actual value can be retrieved by dividing by 100 for the most accurate possible decimal value, which does not accumulate error over time.

This is why it’s often common to see financial systems working in cents, for example, rather than fractions of a dollar.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.