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

How to convert a decimal into an integer?

When I use droolingzombie to test the health bar, it result a very long decimal, I want to convert it into an integer. Any solution?

local player = game.Players.LocalPlayer
local humanoid = player.Character:WaitForChild("Humanoid")
local Label = script.Parent

while true do
	local health = humanoid.Health
	Label.Text = health
	wait(0,1)
end

1 comment

2 answers

✓ Accepted answer

Question

How to convert a decimal into an integer?

Answer

I assume you're asking how to round a number.

We can use the formula floor(x + 0.5) to floor a number. Lua 5.1 has a math library with a floor function so we can use that.

All you have to do is call floor(health + 0.5) and then set the text to that!

###Example Code

This will output 5 because 5.251515215151 rounds down.

local floor = math.floor

local number = floor(5.251515215151 + 0.5)

print(number)

3 comments

0

I use math.floor(health) and it result the same with math.floor(health + 0.5) so what does 0,5 do?

0

.5 is for the rounding.

0

ok i get it, it round numbers

You can use a rounding function like math.floor

local player = game.Players.LocalPlayer
local humanoid = player.Character:WaitForChild("Humanoid")
local Label = script.Parent

while true do
    local health = humanoid.Health
    Label.Text = math.floor(health + 0.5) -- Rounds decimal
    wait(0,1)
end

Or if performance is a must;

local player = game.Players.LocalPlayer
local humanoid = player.Character:WaitForChild("Humanoid")
local Label = script.Parent

while true do
    local health = humanoid.Health
    Label.Text = health + 0.5 - (health + 0.5) % 1 -- Rounds decimal
    wait(0,1)
end

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