Originally Posted by Aanson
Convert 123123 to 123,123 ?
|
This has been floating around a long time, I can't take credit for it. Optimizations and input checking is left as an exercise for the future googler.
Code:
function comma (str)
str = tostring(str) // now you can feed it numbers instead of strings
local prefix, number, suffix = str:match"(%D*%d)(%d+)(%D*)"
return prefix .. number:reverse():gsub("(%d%d%d)","%1,"):reverse() .. suffix
end
print(comma("300"))
print(comma("300g"))
print(comma("-1234g"))
print(comma("$42424242US"))