Format number to use comma in Lua?

Posted by Darwin on Mon 17 Mar 2008 03:39 AM — 6 posts, 31,596 views.

USA #0
I was wondering if there was a simple way to format long numbers (4 or more digits) to use commas in Lua. The PiL book said to refer to a C manual, but C suggests using "%'d" which does not work in Lua.
> print(string.format("%'d", 5000))
stdin:1: invalid option '%'' to 'format'
stack traceback:
        [C]: in function 'format'
        stdin:1: in main chunk
        [C]: ?

Any suggestions?
USA #1
input = arg[1]

input2 = string.gsub(input, "(%d)(%d%d%d)$", "%1,%2", 1)
while true do
    input2, found = string.gsub(input2, "(%d)(%d%d%d),", "%1,%2,", 1)
    if found == 0 then break end
end

print(input)
print(input2)


And running it:

$ lua formatter.lua 100000000
100000000
100,000,000


You need the while loop because it seems that gsub only repeats if you do left-to-right substitution, but this is more of a right-to-left substitution.
USA #2
Oh, and note that %'d doesn't work because it's not in the C standard. 'man printf' indicates that many C runtime libraries are not aware of the ' specifier and will fail to handle it. Since Lua talks straight to the C library in this case, if your C library doesn't handle it then Lua won't either. (That's why Lua refers you to the C manual.)
USA #3
Thanks, David. Works like a charm. :)
Australia Forum Administrator #4
See "Commas in numbers" in post:

http://www.gammon.com.au/forum/?id=7805

The version there handles numbers with decimal places, eg. 100000000.55.
USA #5
Oh, heh, I didn't know about that. I'd definitely recommend Nick's version instead: it handles more cases than my quick hack does, and has good explanations of what is going on.