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

How do I round to the nearest half (0.5)?

Asked by 4 years ago

How would I round to the nearest half? I sometimes get weird decimals like 5.49999999 instead of 5.5 and I want to know how I would round this back to 5.5.

0
Computers usually store numbers as approximations and often there isn't much you can do about it. In Lua, 64^(1/3) (cube root of 64) evaluates to 4. But in Python, 64**(1/3) (also cube root, just different operator) evaluates to like 3.9999999999. programmerHere 371 — 4y
0
I changed my answer. I found a simple way to do it. TheRealPotatoChips 793 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

There isn't any functions to do this. However I have a trick that works everytime.

local number = 1.4 (let's say this)

local minNumber = math.floor(number) (The variable will be 1)

if number < (minNumber + .25) then -- if the number is smaller than 1.25 (min number + .25)
    local RoundedNumber = math.floor(number) -- the rounded number is 1
elseif number >= (minNumber + .75) then -- if the number is higher than 1.75 (minnumber + .75)
    local RoundedNumber = math.floor(number) + 1 --the rounded number is 2
end

if number >= (minNumber + .25) then
    if number < (minNumber + .75) then
        -- if the number is between 1.25 and 1.75
        local RoundedNumber = math.floor(number) + .5 -- the rounded number is 1.5
    end
end

The function math.floor delete all decimals from the number, without rounding the number. Example:

print(math.floor(1.9999))

--OUTPUT

1

You may wonder why, at line 7 and 12, I added a "=". It's because when the number is equal to 1.25, we want it to round it to 1.5 (it's a rule). If the number is equal to 1.75, we want it to round it to 2 (it's a rule)

You can also do:

local number = 1.4

local roundednumber = math.floor(number*2) /2

print(roundednumber)

--OUTPUT

1

I would suggest this way, cuz it's less writing.

Hope this helped!

Ad

Answer this question