Stopwatch using string.format()

Hello! I’m making a stopwatch for my game. The problem is that I can’t get it to be 0:01.555, as it instead returns 0:1.555.

This is the code I’m using:

TimeLabel.Text = string.format("%i:%0.3f", math.floor(Timer / 60), Timer % 60)
TimeLabel.Text = string.format("%d:%06.3f", math.floor(Timer / 60), Timer % 60)
2 Likes

I see the use behind %f and feel super dumb for not having noticed it before. Pro tip though: Luau has a floor-division operator //. You should also explain why his previous pattern was faulty

1 Like

os.date("!%X") converts the second argument into a HH:MM:SS format

local time = 1.555

local function hhmmss(t: number)
	local frac = math.round(1000 * select(2, math.modf(t)))
	
	return os.date("!%X", t) .. "." .. tostring(frac)
end

local function mmss(t: number)
	local frac = math.round(1000 * select(2, math.modf(t)))

	return string.sub(os.date("!%X", t) .. "." .. tostring(frac), 4, -1)
end

print(hhmmss(time)) --- 00:00:01.555
print(mmss(time)) --- 00:01.555
1 Like

This is some next-level overkill…

4 Likes

its really not, im just stripping the decimal places from t then appending it to os.date()

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