local str = "1234" --input string local output = "" --result str = string.reverse(str) --reverses the string so that the , go in the correct place for i=1 , string.len(str) do --loop through all characters if i % 4 == 0 then --uses modulo which is the remainder from the division of i/4 output = output .. "," .. string.sub(str, i, i) --adds in the , incuding the number else output = output .. string.sub(str, i, i) -- no , needed end end output = string.reverse(output) --puts the string back to its correct format print(output) -- prints the result
kingdom5 provided this script and it works well but whenever i get past the hundred thousands it adds an extra digit to the thousands place instead of moving to the millions. Please help me
Change the script to be work if you use if i % 3 == 1 and i > 0 then
instead of if i % 4 == 0
.
I recommend looking at http://lua-users.org/wiki/FormattingNumbers
ex, they have this function:
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
ex, comma_value(1234567890) --> 1,234,567,890
If you have a string, you can use tonumber
to convert it into a number.