Calculating the percentage of votes

Hello! I’m trying to create a voting system and I’m currently working on my function that counts the votes and generates percentages for each candidate based on the total amount of votes submitted.

The problem is that although I have different values for each candidate, one of the candidates keep getting 100% which is false.

Here is my code and below it is the image of what I get as the final result

CODE


local function countBallots()
	local pages = BalletStorage:GetSortedAsync(false, 100)
	local data = pages:GetCurrentPage()
	
	local totalVotes = 0
	
	local livePercentage = {}
	
	for i, v in pairs(data) do
		local candidacyData = CandidateData:GetAsync(v.key)
		ReplicatedStorage.Candidates[candidacyData.candidate].Value += 1
		totalVotes += 1
		print(ReplicatedStorage.Candidates[candidacyData.candidate].Name.." now has "..ReplicatedStorage.Candidates[candidacyData.candidate].Value.." votes!")
	end
	
	task.wait(1)
	
	-- Generate percentages
	
	for _, ballot in ReplicatedStorage.Candidates:GetChildren() do
		local percentage
		
		if ballot.Value == 0 then
			percentage = 0
		else
			percentage = math.floor(math.floor((ballot.Value/totalVotes) + 0.5)*100)
		end
		
		print(percentage)
		
		local ballotData = {
			[ballot.Name] = percentage.."%"
		}
		
		table.insert(livePercentage, ballotData)
	end
	
	print(livePercentage)
end

RESULT


How can I fix this bug or error? I’m not getting any specific errors therefore the code is working but the math might be incorrect.

Your math is incorrect. Doing an assessment on your script run results:
-6 votes total, 3 for Becca and 1 for other 3 candidates

-To calculate Becca’s vote (according to your script), we first ballot.Value/totalVotes, which is 3/6 = 0.5. Then we add 0.5 to that, it becomes 1. Then we math.floor it, multiply it by 100 and math.floor again, which results in 1*100 = 100 (%).
For other participants, 1/6=0.16666…, 0.16666… + 0.5 = 0.66666…, and then math.floor rounds it and results in 0 (%). To fix the voting, you’d first need to remove the + 0.5 and the first math.floor, and only flooring the result. That way, 3/6=0.5, 0.5*100 = 50, and math.flooring 50 results in 50(%). Similarly, 1/6 = 0.1666…, 0.16666… * 100 = 16.666… %, math.flooring that will give you 16%.

4 Likes

Yeah you’re correct. My math was off so my final results were smaller than they should have been. The correct equation is math.floor(ballot.Value/totalVotes*100).

Thanks a bunch!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.