01 | local str = "1234" --input string |
02 | local output = "" --result |
03 | str = string.reverse(str) --reverses the string so that the , go in the correct place |
04 |
05 | for i = 1 , string.len(str) do --loop through all characters |
06 |
07 | if i % 4 = = 0 then --uses modulo which is the remainder from the division of i/4 |
08 | output = output .. "," .. string.sub(str, i, i) --adds in the , incuding the number |
09 | else |
10 | output = output .. string.sub(str, i, i) -- no , needed |
11 | end |
12 |
13 | end |
14 |
15 | output = string.reverse(output) --puts the string back to its correct format |
16 |
17 | 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:
01 | function comma_value(amount) |
02 | local formatted = amount |
03 | while true do |
04 | formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)" , '%1,%2' ) |
05 | if (k = = 0 ) then |
06 | break |
07 | end |
08 | end |
09 | return formatted |
10 | end |
ex, comma_value(1234567890) --> 1,234,567,890
If you have a string, you can use tonumber
to convert it into a number.