Why is this always return false?

I am making a timer and it decrements by 0.1 seconds and only display the digit when it is a integer but the isInteger(x) function always returning false. Am I doing it correctly?

[lua]local timeCount = 30

local function isInteger(x)
return math.floor(x) == x
end

local function countdown()
timeCount = timeCount - 0.1
if(isInteger(timeCount)) then
displayTimerDigit()
end
end[/lua] [import]uid: 40786 topic_id: 13552 reply_id: 313552[/import]

That looks like it should work, but why not drop a print in the isInteger function to see if timeCount is ever an int.

Or why not just have displayTimerDigit() show math.floor(timerCount)?
[import]uid: 19626 topic_id: 13552 reply_id: 49779[/import]

Sorry i type it wrong should be math.floor instead but i print out both math.floor(x) and x and when its reaches the same digit example 9 == 9 it still return false.

[lua]local function isInteger(x)
print(“math.floor”…math.floor(x)…" "…“timecount”…x)
local integer = (math.floor(x) == x)
print(integer)
return integer
end[/lua] [import]uid: 40786 topic_id: 13552 reply_id: 49785[/import]

I’m new to this, but it seems like a bad idea to assume that a float that is decrementing by 0.1 will do it perfectly. The “9” might be a 8.99999999999, because of how floats are represented, and not be == 9.

So instead of using:

local function isInteger(x) return math.floor(x) == x end

… I’m curious if this would behave as expected:

local function isInteger(x) return ((x - math.floor(x)) \< 0.001) or ((math.ceil(x) - x) \< 0.001) end

[import]uid: 37155 topic_id: 13552 reply_id: 49970[/import]

Confirmed the problem is that floats are not “precise”. Used your original isInteger() function, which didn’t see any integers. Then tested with the following:

local timeCount = 30  
   
local function isInteger(x)  
 return ( x - math.floor(x) \< 0.001 ) or ( math.ceil(x) - x \< 0.001 )  
-- return math.floor(x) == x  
end  
  
while timeCount \>= 0 do  
 timeCount = timeCount - 0.1  
 if(isInteger(timeCount)) then  
 print(timeCount.." is an integer")  
 else  
-- print(timeCount)  
 end  
end  

All expected values were close enough to be considered integers. Interestingly, the last few lines showed the gradual accumulation of errors in the floats:

13 is an integer 12 is an integer 11 is an integer 9.9999999999998 is an integer 8.9999999999998 is an integer 7.9999999999998 is an integer 6.9999999999998 is an integer

So, moral is not to assume that math is “precise”. [import]uid: 37155 topic_id: 13552 reply_id: 50026[/import]