I came across this block of code that takes a large number and returns the number with commas. I have no idea why this works, so if anyone could explain it that would be great.
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
If you want more info essentially it is continuously searching for a number with three digits at the end, then adding the comma to the beginning of those three digits. ^ matches only at the beginning of the string, groups are denoted by parenthesis (Which is what the %1 and %2 reference, the first and second group), and digits are represented by %d. The β+β operator signifies one or more. β-?β means that it will match 1 or 0 β-β, essentially saying that the number can be negative or positive. If you removed that then it would only work with positive numbers.
So in English, it would go something like, match any number of digits starting at the beginning of a string, then exactly after that match three digits, and put a comma in between those two groups. Then iterate until you canβt find any amount of digits followed by three digits, or in other words until it has been fully formatted. You can see this more clearly by just seeing how the first iteration would affect a number. It would go from something like β15000250β to β15000,250β then in the second iteration β15,000,250β. You can see from the original text to the first iteration that you have 1 or more digits (β15000β) followed by three digits (β250β), then it simply places a comma in between the groups.