10 < 10 prints true?

local seconds = 550
local timeInMinutes = seconds/60
local minutes = math.floor(timeInMinutes)
local seconds = (timeInMinutes-minutes)*60
if seconds < 10 then
	print(seconds.." is less than 10")
	seconds = "0"..seconds
end
print(minutes..":"..seconds)

Outputs:

10 is less than 10
9:010


The code above states that 10 is less than 10, which should clearly be false. Am I missing something really obvious here?

1 Like
> print(string.format("%.16f", seconds))
9.9999999999999645

You’ve run into floating point inaccuracies - Lua numbers can’t represent fractions like 550/60 exactly, so when you subtract 9 (the number of minutes) from it and multiply it by 60, you don’t get exactly 10. print hid this from you because it rounds numbers passed to it to some precision.

Read more here

11 Likes

Nice explanation, makes sense now.

Changing it to local seconds = math.ceil((timeInMinutes-minutes)*60) gets it to work.

Thanks

1 Like

I’d recommend rounding by doing:

local seconds = math.ceil( ( timeInMinutes - minutes ) * 60 - 0.5 )

In this instance your floating point error made it low, but with different inputs your floating point error could make it high, so 9.000000001 would round to 10. Using the -0.5 ensures you round to the closest integer.

2 Likes
2 Likes