Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is rounding a float to a decimal instead of an integer possible?

Asked by 2 years ago

math.round only rounds to the closest integer, which I cannot use in my case. I need a way to round to a decimal, so a function that goes kind of like this:

local rawfloat = 0.6328
local roundedfloat = round(rawfloat,1) -- first arg is the float, second arg is to what decimal to round
print(roundedfloat) --> 0.6

Any help with this would be greatly appreciated, as I am not the greatest at math and therefore don't know how I would make this.

0
you can use string.format to accomplish it. JesseSong 3916 — 2y
0
check @greatneil80's answer JesseSong 3916 — 2y

1 answer

Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

I probably overdid it, made this in like 5 minutes:

local function RoundDepth(num,depth)
    return tonumber(string.sub(num,1,string.find(num,'%.'))..math.ceil(tonumber(string.sub(num,string.find(num,'%.')+1,string.find(num,'%.')+depth))-.5))
end
print(RoundDepth(811324234.499429924,4))


To understand more,

local function RoundDepth(num,depth)
    local n = tostring(num)
    local x = math.ceil(tonumber(string.sub(n,string.find(n,'%.')+1,string.find(n,'%.')+depth))-.5)
    return tonumber(string.sub(num,1,string.find(n,'%.'))..x)
end
print(RoundDepth(811324234.499429924,1))

You can replace the ceil with round, I just like using ceil apparently.

This basically turns the number into a string, gets the ".", gets the numbers after it, depending on how deep it is, suppose it was 2, 49 would round to 50 in 811324234.499429924.

x is basically me rounding the end of the number after the decimals by the depth the last part after return is me joining the original number (without the decimals) along with the new rounded number.

If you have questions let me know.

Here is the link to the interpreter with the code: runnable code

Edit: If the code in the first part is cut off, click view raw to see it whole

Ad

Answer this question