To format numbers by adding commas to them, you can use the following code:
-- Function to add commas to a number
local function formatNumber(n): number?
n = tostring(n)
return (n:reverse():gsub("...", "%0,", math.floor((#n - 1) / 3)):reverse()) :: number
end
-- Example usage
local plr = game:GetService("Players").LocalPlayer
local level = plr:WaitForChild("Player Stats").Level
local xp = plr:WaitForChild("Player Stats").XP
local reqxp = plr:WaitForChild("Player Stats")["Required XP"]
local text = script.Parent
-- Use string.format to display the formatted XP and required XP values
text.Text = string.format("%s/%s", formatNumber(xp.Value), formatNumber(reqxp.Value))
level.Changed:Connect(function()
text.Text = string.format("%s/%s", formatNumber(xp.Value), formatNumber(reqxp.Value))
end)
xp.Changed:Connect(function()
text.Text = string.format("%s/%s", formatNumber(xp.Value), formatNumber(reqxp.Value))
end)
The formatNumber function takes a number as an input and returns the number with commas inserted every three digits, starting from the right. It does this by converting the number to a string, reversing the string, and using the gsub function to insert commas after every three digits. Finally, it reverses the string again to restore the original order of the digits and returns the resulting string.