How does this code work?

so I recently searched in dev forum how to add commas to big numbers and I found out that there is a document that gives you Lua functions for formatting numbers,

and I was wondering if this code really makes sense

function comma_value(amount)
  local formatted = amount
  while true do  
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
    if (k==0) then
      break
    end
  end
  return formatted
end

it looks really weird to me and I’m not sure how it works and I’m wondering is there any simpler way to implement commas to numbers without using this function that contains random percentages?

or someone who understand how it works can you please explain it?

1 Like

That code might work but it’s hard to tell without thoroughly testing it to be honest. If you’re looking to add commas to big numbers, I would recommend this great devforum resource:

Otherwise, I would test the code yourself and see if it works.

It’s using Lua patterns. There a whole different thing than regular Lua, so it looks a little strange.

http://lua-users.org/wiki/PatternsTutorial

oh thanks for linking me to this post it will be useful for future projects, but that wasn’t my what I was looking for in the first place, I was just wondering how the formatting for commas work and if someone can explain it or present a more simple way for it, but still thanks for the post.

You can also loop through the string and add commas with some more readable string functions.

(edit: i.e. convert the number to a string then loop through)

The “%d” represents “digit”
The code is using string functions to locate each block of 3 digits (%d%d%d)
and append the comma for formatting.

I use this lately, a copy and paste from StackOverflow.

function format_int(number)
	local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
	-- reverse the int-string and append a comma to all blocks of 3 digits
	int = int:reverse():gsub("(%d%d%d)", "%1,")
	-- reverse the int-string back remove an optional comma and put the 
	-- optional minus and fractional part back
	return minus .. int:reverse():gsub("^,", "") .. fraction
end