Hello all, just a simple question I have: how can I format a number to include commas between groups of three zeros? I’m pretty sure this is possible with string.format but I could be wrong… any help would be appreciated!

I tried looking up the documentation for string.format but I only found decimal formating (300 → 300.00), didn’t find anything on the devforum.

I’m looking to make values like 2000 display as 2,000.

Thanks! This works very well, but for some reason when I put this in the command bar it gives two numbers?
formatNumber(1000) → 1,000 1

Also this doesn’t work with anything greater than 1 million but that’s fine, the most my items will cost is probably around 10,000
Idk why the 1 appears, it happens with other numbers too

That’s because gsub returns not only the number, but the number of times that pattern occurred. See here: string | Documentation - Roblox Creator Hub for further information

You didn’t put in the right search terms then. You need to spend time searching. You cannot just have a one-off search and call it “no results”. I simply searched up “number commas” and enough threads to have an understanding of how to do this turned up: no excuse on your part.

Well then you could use it like this if you have even smaller numbers e. g. 1550 you will have to play around with code:

local value = 1500
if value > 999 then
local sd = value/1000
if math.floor(sd)%sd~=0 or math.ceil(sd)%sd~=0 then
local minus = (sd-math.floor(sd))*10
local minus2 = (sd-math.floor(sd))
if sd-math.floor(sd)>=0.5 then
local sdtwo = sd-minus2
print(tonumber(sdtwo)..","..minus.."00")
else
print(sd..",".."000")
end
end
end

The fourth argument of gsub can be used to guarantee there is no extra comma, instead of an extra gsub call.

local function formatNumber(n)
n = tostring(n)
return n:reverse():gsub("...","%0,",math.floor((#n-1)/3)):reverse()
end
print(formatNumber(1000)) --> 1,000