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

How to round to the nearest hundredth?

Asked by 7 years ago

So I've looked everywhere for a good way to round. I've tried using math.floor and math.ceil, But I can never make it round to the nearest hundredth. Can anyone help?

1 answer

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

This isn't too hard. There might be a better way, but as an example, you can use math.floor. This rounds to the nearest whole number:

--// Nearest Whole Number
local function round(num)
    return math.floor(num+0.5)
end

You can change this to round to tenths:

--// Nearest Tenth
local function round(num)
    return math.floor(((num*10)+0.5))/10
end

And so on:

--// Nearest Hundredth
local function round(num)
    return math.floor(((num*100)+0.5))/100
end
0
Thanks! It worked! I'm not very good at math... theamazemanII 32 — 7y
1
Good answer. You can generalize it with "function round(num, decimals) return math.floor(num*10^decimals+0.5)/10^decimals end" if desired. chess123mate 5873 — 7y
0
Oh, That's pretty cool. theamazemanII 32 — 7y
Ad

Answer this question