Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Rounding a decimal to a whole number?

What I'm trying to do is make a custom health bar GUI, it works, but instead of having numbers like 61.012410005 it would round to the nearest whole number.

My code.

local percent = script.Parent.Indicator.Percent
local indicator = script.Parent.Indicator
local player = game.Players.LocalPlayer
workspace:WaitForChild(player.Name)
local char = game.Workspace[player.Name].Humanoid

char.Changed:connect(function()
	indicator.Size = UDim2.new(char.Health/100, 0, 1, 0)
	percent.Text = char.Health
end)


--to test it
local takeaway = math.random(1,50)
wait(20)
char.Health = char.Health - takeaway

1 answer

✓ Accepted answer

Simple, just use math.floor. This function allows you to convert any decimal number, to it's next whole number. However, note that this function doesn't actually round anything. Here's an example:

print(math.floor(1.1)) -- Prints 1

print(math.floor(1.9)) -- However this still prints 1, even though it's closer to 2

Rounding

If you want to actually round the whole number based on it's decimal number, just add 0.5 to the math.floor process. This is just used to see if adding half a whole number will change it's initial whole number value, and if it does, return it. Here's an example:

local function Round(x)
	return math.floor(x+0.5) -- Add 0.5 to x
end

print(Round(1.2)) -- prints 1

print(Round(1.9)) -- prints 2

Hope that helped. Let me know if you have any questions.

1 comment

0

10x more simpler than my way of rounding xD

This discussion is preserved as it was. New answers, comments, and votes are closed.