Since string.format doesn't have a format for that you will have to create your own.
function addComas(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
print(addComas("250000000"))
print(addComas("25000000"))
250,000,00
25,000,000
Explaining the code:
We are using three functions
string.reverse(str): It reverses str, so "Hi" becomes "iH"
string.sub(str, start, [end]): Where end is optional, it returns the substring from start to end. So string.sub("Hello", 2) returns "ello"
string.gsub(str, pattern, replace, [n]): This is quite complicated, it searches str for matches using pattern and then replaces it with replace, n is optional and it's the number of maximum substitutions it is allowed to make. So string.gsub("Hello", "llo", "lp") returns "Help"
Then we put everything together:
Let's take "250000" for example, if we use string.gsub("25000", "(%d%d%d)", "%1,") it will return 250,00 because it searches the string from left to right, so we have to reverse it.
string.reverse("25000"):gsub("(%d%d%d)", "%1,") will return "000,52" so we reverse it again to revert the process. string.reverse("25000"):gsub("(%d%d%d)", "%1,") :reverse() and that's it.
There is a problem if the string length if multiple of three, like "250" because it will become ",250" so in order to fix that we just check if it's multiple of 3 and if it is we remove the first character, that's the comma.
EDIT: There was a bug in the code where "250000" would become ",250,000" that's is if the number of digits was multiple of three, so if it is then we just remove that.
1 comment
Please put your code in a lua box so it's easier for us to read.