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

How would you add commas to integers?

I'm trying to add commas to integers, for example:

x = 5000
print(x) --> 5000

I want commas in between each three digits. So I want it to be:

--> 5,000

2 answers

✓ Accepted answer
x = 5000

function commas(str)
   return #str % 3 == 0 and str:reverse():gsub("(%d%d%d)", "%1,"):reverse():sub(2) or  str:reverse():gsub("(%d%d%d)", "%1,"):reverse()
end

-- you need convert the value to string (using tostring())

print(commas(tostring(x)))

2 comments

0

i have an odd feeling this was taken from another answer

0

Yes, from "Destrings" answer

I know I'm a little bit late, but I figured I'd show my take at converting a number to comma format. This works with negative numbers as well.

function ConvertNumber(num)
	local newNum = nil--This variable is the final product, and will be what prints to the output
	local numRev = string.reverse(num)--The first of the reversed numbers
	local numRev2 = string.reverse(num)--The second of the reversed numbers

	local stringLen = string.len(num)
	local amntOfTimes = stringLen / 3 --This divides the string length by 3, which is also how many spaces are in between commas. 
	local tempAmntOfTimes = tostring(amntOfTimes)--This plays into the function below

	if string.len(tempAmntOfTimes) == 1 then--This function checks to see if the integer value of amntOfTimes is a decimal or whole number. If it is a whole number it subtracts one from the value. This is so there isnt a comma at the beginning of the number
		amntOfTimes = amntOfTimes - 1
	end

	local x = 3--This value is how many spaces the next comma needs to be
	local n = 0--This value offsets the comma to be in the correct spot

	for i = 1, amntOfTimes do
		numRev = string.sub(numRev, 1, x+n)..','..string.sub(numRev2, x+1, stringLen)--Everything comes together here
	
		n = n + 1
		x = x + 3
	end


	local newNum = string.reverse(numRev)--ReReverses the number to make it look normal
	print(newNum)
end

ConvertNumber(5000)--Put the number you want to convert here

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