I am making a building game and i want to make a grid snap feature so you can place items on a grid, the problem is that i’m using math.round
which rounds to the nearest whole, and if you want to snap for every 0.1 (example would be 5.87 = 5.9) it would just round to the whole. Is there a better way of doing this rather than math.round
?
2 Likes
You could multiply the number by 10, round it, and then divide by 10.
Here’s an example of these steps in order:
1.47 > 14.7 > 15 > 1.5
Use string.format:
function roundNumber(num, numDecimalPlaces)
return tonumber(string.format("%." .. (numDecimalPlaces or 0) .. "f", num))
end
print(roundNumber(4.6787673219385, 1)) --prints 4.7
print(roundNumber(4.6787673219385, 2)) --prints 4.68
print(roundNumber(4.6787673219385, 3)) --prints 4.679
3 Likes
local randoms = math.random(5870, 5890)
randoms /= 1000
print(randoms)
Using your example.
1 Like
To round to any number you have to add by half of that number. Then apply the modulus operator with the rounding number as your. (€If you are rounding to the nearest int then just use math.floor instead.)
local function(number, roundToNearest)
number += roundToNearest / 2
return roundToNearest % number -- If this is incorrect it will be the other way around.
end
what I did for my game is round the number by multiplying and deviding it as @deepsolace mentioned. For example my code was this:
local roundeddamage = math.floor(damage * 10) -- change damage to the variable you use.
local devideddamage = roundeddamage / 10
damage = devideddamage
This would make the damage rounded to 1 decimal. If for some reason you want more decimals you can add a 0 to the 10 to add 1 more decimal.