how do i round decimals like
1.23891273 > 1.23
1.000569229 > 1.00057
1.0421 > 1.042
1.004505 > 1.0045
i did not find any solution on this on the devforum
how do i round decimals like
1.23891273 > 1.23
1.000569229 > 1.00057
1.0421 > 1.042
1.004505 > 1.0045
i did not find any solution on this on the devforum
You can divide the number by an increment, round it, then multiply it by the same increment. You do need to know what the increment should be, though. It can be any number, not limited to a number < 1.
local increment = 0.01
local number = 349.493245
number = math.round(number / increment) * increment --> 349.49
You can use a combination of string.format()
and tonumber()
to easily achieve what you want without using any extra variables.
local num1 = 1.000569229
local num2 = 1.0421
num1 = tonumber(string.format("%.5f", num1))
num2 = tonumber(string.format("%.3f", num2))
print(num1) -- 1.00057 as number
print(num2) -- 1.042 as number
but i have to manually check how much decimal places is there any way to make it so i dont have to do that
Use %g instead of %f chars chars
You can check number of zeros after decimal point with a loop then just add that number to the string format:
local function checkzeros(num)
local zeros = 0
local numstr = tostring(num)
local decpoint = string.find(numstr,"%.") or 0
for i=decpoint+1, #numstr do
if string.sub(numstr,i,i) ~= "0" then break end
zeros+=1
end
return zeros
end
local num = 1.0046988
num = tonumber(string.format("%.".. checkzeros(num)+2 .."f", num)) -- 1.0047
There’s lots of solutions here, but why do you need to do this? That will help you decide which one to choose.
i already thinked of this solution, but thanks alot!
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.