String Seperation

How would i split a string up every 3 characters starting from the right?
So if you had

100000 it turns into 100,000

The functions been posted before but i cant find it.

Like that?

Use . if you don’t want to specify a type.

Sort of like that but it needs to put the , in as well.

[editline]27th June 2011[/editline]

It also doesnt output the numbers if its not a multiple of 3.
It simply needs to slot some commas in.

I would do something like this…


function formatint( intNumber )
local str = tostring( intNumber )
if( string.len( str ) < 4 ) then return; end

for mat in string.gmatch(str, "(%d%d%d%d-)") do //flaps code
	return mat;


I dont really know how to add the commas in there though.

function Something(msg)
local text = string.reverse(msg)
local zreturn = “”
local count = 0
if (string.len(text) > 3) then
for i=1,string.len(text) do
count = count + 1
zreturn = zreturn…string.Left(text,1)
text = string.Right(text,string.len(text)-1)
if (count == 3) then
zreturn = zreturn… “,”
count = 0
zreturn = string.reverse(zreturn)
if (string.Left(zreturn,1) == “,”) then
zreturn = string.Right(zreturn,string.len(zreturn)-1)
return zreturn

Took me a few minutes to figure out

When given: 12345671238
returns: 12,345,671,238

EDIT: Fixed a problem
(if you had put 123456 then it would return ,123,456)

Thanks for that man.
I was gonna do it like that but I was looking for a way with patterns.

Either way, that will do.

local function formatNumber(n)
if (!n) then
return 0
if n >= 1e14 then return tostring(n) end
n = tostring(n)
sep = sep or “,”
local dp = string.find(n, “%.”) or #n+1
for i=dp-4, 1, -3 do
n = n:sub(1, i) … sep … n:sub(i+1)
return n
Credits to Banana Lord.

function AddCommasToInt(str)
str = string.reverse(tostring(math.floor(tonumber(str))));
local len = string.len(str);
local ret = “”;
for i=1,len do
ret = ret … string.sub(str,i,i);
if((i%3) == 0) then
ret = ret … “,”
return string.reverse(ret)

Should be faster though.

Thanks for all these guys.

what does i%3 do?

Its a binop, found that in my manual… wtf is a binop.

% is modulus in programming languages, basically the remainder from a division operation. In that example, if i divided by 3 doesn’t leave a remainder, add a comma, if it does. Continue looping without adding a comma.

That makes sense. Never used that before