Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

can't round the value to a whole number?

Asked by
0msh 333 Moderation Voter
4 years ago

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)
1
Why do you have an inf loop in the player added event? This will create a new loop every time a player joins. User#5423 17 — 4y
0
The rouding function works as expected. User#5423 17 — 4y
0
^ LordLightingXII 12 — 4y
0
not for me, I'll just use an IntValue instead I guess 0msh 333 — 4y
1
You never use the value returned by round ..... User#5423 17 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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.

Ad

Answer this question