Hey Everyone,
So I’m making a health GUI for my story game. It works fine, but when a player looses health, it will often display the numbers as huge decimals, e.g. 62.3922525. This is a problem. I want to make it so that it will only show whole numbers, so instead of 62.3922525 it will just show 62.
Here is my script:
Player = game.Players.LocalPlayer
repeat wait() until Player.Character
script.Parent.TextLabel.Visible = true
Player.Character.Humanoid:GetPropertyChangedSignal('Health'):Connect(function()
script.Parent.TextLabel.Text = 'Health: '..Player.Character.Humanoid.Health
end)
How can i achieve this?
It’s a local script. Thanks for any help!
check if the tenths place through a script in the decimal is greater than or equal to 5, then use math.ceil, if not, math.floor
Ex: 6.932992382832 math.ceil = 7% health
Ex2: 5.11111189238028283 math.floor = 5% health
function Round(n, decimals)
decimals = decimals or 0
return math.floor(n * 10^decimals) / 10^decimals
end
print(Round(math.pi, 3)) -- pi as example because it's a long number
For more freedom if you would ever want a certain amount of decimals behind the rounded number.
Remember that there’s an event signal specifically for when the health is changed. But yes, that’s not completely off either.
I’d however do it like this:
local LocalPlayer = game.Players.LocalPlayer
local Character = LocalPlayer.Character or LocalPlayer.CharacterAdded:Wait()
script.Parent.TextLabel.Visible = true
--|| Functions
function Round(n, decimals)
decimals = decimals or 0
return math.floor(n * 10^decimals) / 10^decimals
end
function HealthChanged(NewHealth)
script.Parent.TextLabel.Text = 'Health: ' .. tostring(Round(NewHealth)) -- you don't need to include a decimal if you want none
end
--|| Connections
Character:WaitForChild("Humanoid").HealthChanged:Connect(HealthChanged)
For additional functionality I like to use an implementation that lets you set the base number to something other than 10.
local module = {
e = math.exp(1),
pi2 = math.pi * 2
}
function module.isReal(n)
return ((typeof(n) == "number") and (n == n) and (math.abs(n) ~= math.huge))
end
function module.isInt(n)
return module.isReal(n) and (math.floor(n) == n)
end
function module.round(x, degree, base)
assert(module.isReal(x), "Input must be a real number.")
if (degree ~= nil) then
assert(module.isInt(degree), "Degree must be an integer.")
else
degree = 0
end
if (base ~= nil) then
assert(module.isInt(base), "Base must be an integer.")
assert((base > 0), "Base must be greater than zero.")
else
base = 10
end
local n = base ^ degree
return math.floor(x * n + 0.5) / n
end
return module
That way you can do stuff like round to the nearest 5 or any integer.