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

How do I find a percentage of a value?

Here's what I tried:

function updatePercentage()
	local prcnt = game.Workspace.ShotsHit.Value/game.Workspace.ShotsFired.Value
	script.Parent.Text = prcnt.."%"
end

game.Workspace.ShotsFired.Changed:connect(updatePercentage)

I'm simply trying to find the percentage of how many times the target is hit out of all shots fired (and yes the values are set up correctly). Also, if you could please throw in a rounding system that would be great.

1 answer

The percentage of anything is always attempts / total, no matter what form it's in (in this case, it'd be successful shots / total shots)


All you'd have to do to get the percentage of how many successful shots to total shots, would be to keep track of both. Here's an example:

local Shots = 0
local Hit = 0

-- "Shot" will be the function that increments our stats
 local function Shot(state)
	if state then -- If we pass true, then
		Hit = Hit + 1 -- Increment our hit count
	end
	Shots = Shots + 1 -- Incrememnt our total no matter what
end

local function UpdatePercentage()
	print("Hit rate is: "..(math.floor(Hit/Shot)).."%")
end

Shot(true) -- Successful hit
Shot(true) -- Successful hit
Shot(true) -- Successful hit
Shot(false)  -- Unsuccessful hit

UpdatePercentage() -- Will print 75%

Hope that helped.

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