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

Can you round numbers to the nearest decimal value?

Asked by 8 years ago

I know you can round up/down to the nearest whole number, but is there a way to round to the nearest decimal value?

i.e. Is there a way to round the number 3.48888888888888888888 to 3.5 instead of rounding the entire number down to 3?

2 answers

Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

Divide by the interval, round, multiply by the interval. If you take 34 and divide it by 10 and round that, then multiply by 10, you get 30.

function round(x,near)
    return math.floor(x/near+.5)*near
end
Ad
Log in to vote
1
Answered by 8 years ago

What you can do is change the decimal power of the number, round it and then set the decimal power back.

function roundToNearest(number, decimals)
    local decimalPower = math.pow(10, decimals)
    local powered = number * decimalPower  -- We power the number up so we can round the decimal part and not the whole number

    local round = math.floor(powered + 0.5) -- We add 0.5 so it rounds, instead of flooring or ceiling
    local final = round / decimalPower -- Bringing back the power

    return final
end

The decimals argument is how many decimal points you want to preserve. You can use negative numbers to round the whole part, 0 to return only the whole part and positive numbers to round the decimals.

Hope this helped.

Answer this question