Is there any straightforward way to do this, for example if I had the number 12.345 and needed to find which number out of 23.456, 1.234 or 5.678 was closest?
Any help would be appreciated.
Is there any straightforward way to do this, for example if I had the number 12.345 and needed to find which number out of 23.456, 1.234 or 5.678 was closest?
Any help would be appreciated.
Would you want it to find the greatest number or smallest?
Thanks
Not the greatest or smallest, the closest to a specified number. I know that you can use math.floor() for smallest, but I was just wondering if there’s a method for getting the closest number.
If your numbers aren’t sorted, you’ll have to go through the entire list to check. Here’s some code.
local numbers = {23.456, 1.234, 5.678} -- List of numbers to check local targetNumber = 12.345 -- Target number local minDiff = math.huge local closest = 0 for i = 1, #numbers do local diff = math.abs(targetNumber - numbers[i]) -- Find the difference between target and this one if diff \< minDiff then -- If it's closer than our current closest... minDiff = diff -- ...set the new closest difference... closest = numbers[i] -- ...and set the closest number to this one end end print("The closest number to " .. targetNumber .. " is " .. closest)
Would you want it to find the greatest number or smallest?
Thanks
Not the greatest or smallest, the closest to a specified number. I know that you can use math.floor() for smallest, but I was just wondering if there’s a method for getting the closest number.
If your numbers aren’t sorted, you’ll have to go through the entire list to check. Here’s some code.
local numbers = {23.456, 1.234, 5.678} -- List of numbers to check local targetNumber = 12.345 -- Target number local minDiff = math.huge local closest = 0 for i = 1, #numbers do local diff = math.abs(targetNumber - numbers[i]) -- Find the difference between target and this one if diff \< minDiff then -- If it's closer than our current closest... minDiff = diff -- ...set the new closest difference... closest = numbers[i] -- ...and set the closest number to this one end end print("The closest number to " .. targetNumber .. " is " .. closest)