I am working on a math function which requires the use of the modulo operator. However, I noticed slight inaccuracies in it’s calculation. Here’s what I mean:
(This also happens with other alternatives I’ve seen)
Are there any alternatives or fixes for this?
NOTE: All I’m trying to do is remove numbers before the decimal point
AFAIK your original solution is the only way I know.
Usually these inaccuracies don’t matter all the much in calculations and the only problems that they cause typically involve displaying text to the user, which is what the other solution is for.
I would usually just leave it alone since it’s not a big deal but if it really matters, go ahead with either for the above.
Try this (decimalPlaces is how many you want to round to, so in your case, pass in 2):
local function ClearFloatingPointError(number, decimalPlaces)
local str = tostring(number)
decimalPlaces = math.max(decimalPlaces, 0)
local formatted = string.format(`%.{decimalPlaces}f`, number)
formatted = formatted:gsub("%.?0+$", "") or 0
return tonumber(formatted)
end
As I’ve stated in the original post, this still comes with inaccuracies. Not all floating points go up, some go down by 0.000000001.
The actual solution is this:
local number = 1.37
local digits = 2
(string.format(`%0.{digits}f`, number)*10^digits)/10^digits
oh i meant to use math.round, that would solve the issue. your solution converts it to a string, which isn’t really efficient if you want to do more math operations on it and sometimes might cause errors.