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

can't round the value to a whole number?

it's suppose to round the gold value in leaderstats to a whole number, but instead, if it's "2.8", it would turn into "2.7999999999999998224"

local function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
    return math.floor(num * mult + 0.5) / mult
end

game.Players.PlayerAdded:Connect(function(plr)
	while wait(1) do
		local value = plr:WaitForChild("leaderstats").Gold.Value
		if value%1 > 0 then
           round(value)
		end
	end
end)

5 comments

1

Why do you have an inf loop in the player added event? This will create a new loop every time a player joins.

0

The rouding function works as expected.

0

^

0

not for me, I'll just use an IntValue instead I guess

1

You never use the value returned by round .....

1 answer

As kingdom5 says, you call round but then don't use what it returns. round doesn't modify the NumberValue in your leaderboard, so nothing's happening.

The simplest rounding method is math.floor(value + 0.5). So, you could do:

game.Players.PlayerAdded:Connect(function(plr)
	local gold = plr:WaitForChild("leaderstats").Gold -- get the NumberValue once; don't access its .Value until we need it, since it can change over time
    while plr.Parent do -- Ensure the loop exits when the player has left the game (thanks to kingdom5 for pointing this out)
	wait(1)
        if gold.Value % 1 > 0 then
           gold.Value = math.floor(gold.Value + 0.5)
        end
    end
end)

You might also consider listening for its .Change property (since this is more efficient than checking every second), but at this point it would be better to use an IntValue.

Although I don't think you need it here, it's generally better to use a function (ex in a ModuleScript) like SetPlayerGold(player, gold) rather than modifying a value directly and then having other scripts try to correct it. So, in this case, SetPlayerGold could round the gold parameter automatically.

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