Countdown Timer prints with loads of excess decimals

Hello, today I’m having an issue with this countdown code.

What is the issue:
At the last second on the timer it will print out 0.90002, 0.80002 etc. There has been no errors in the output either.

What I want to achieve:
print 0.9, 0.8, 0.7 and so on.

What I’ve tried so far:
I have tried so far is math.floor(i). However this didn’t seem to work as though it counts by whole numbers

What I think might be the issue:
Potential lag, or maybe Delta Time issues?

script.Parent.MouseButton1Click:Connect(function()
	local timeOut = 10
	
	for i = timeOut, 0, -0.1 do
		print(i)
		task.wait(0.1)
	end
end)

Thank you for your assitance!

Use math.round(). This is caused by floating point inaccuracies that you can read online.

script.Parent.MouseButton1Click:Connect(function()
	local timeOut = 10
	
	for i = timeOut, 0, -0.1 do
		i = math.round(i * 1e4) / 1e4 -- Rounds to 4 zeroes
		print(i)
		task.wait(0.1)
	end
end)

Also be careful with using for i = timeOut, 0, -0.1. It won’t activate the very last index if your rate is a repeating decimal like -(1 / 60), or irrational like math.pi.
Consider using an integer instead, like:

local timeOut = 10
	
for i = timeOut * 10, 0, -1 do
	i /= 10
	print(i)
	task.wait(0.1)
end
2 Likes

It worked. Thank you very much!

You can also use string.format

local number = 12.3456
print(string.format("%.02f", number)) --> 12.35
print(string.format("%.03f", number)) --> 12.346
print(string.format("%.05f", number)) --> 12.34500
1 Like