Formatting a currency label to include commas

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.

4 Likes

Here is my quick and simple example on how to do it:

local value = 2000
if value > 999 then 
	local sd = value/1000
	print(sd..",".."000") 
end

I hope this helps. :herb:

This is good, but it doesn’t work if my shop has items worth e.g. 1500, as it will display as 1.5,000
Thanks tho

Here:

local formatNumber = (function (n)
	n = tostring(n)
	return n:reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")
end)

print(
	formatNumber(1000) --> 1,000
)
20 Likes

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

This question has been asked before. Please search before asking.
https://devforum.roblox.com/search?q=number%20commas%20category%3A55

2 Likes

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

1 Like

I did search but nothing came up, sorry

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

I hope this helps. :herb:

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
6 Likes