I needed a routine to insert commas into numbers I was displaying to make them easier to read. So I put together the function ‘addComma’. You can pass it a number or a number string. This might come in handy for anyone who has a game where the score gets really big and they want it to be easier to read.
displayMode(FULLSCREEN)
function setup()
fontSize(40)
end
function draw()
background(40,40,50)
fill(255)
text(addComma(123456.1234),WIDTH/2,550)
text(addComma(123456789/4321),WIDTH/2,500)
text(addComma(1234*5678),WIDTH/2,450)
text(addComma(math.sqrt(1234567890)),WIDTH/2,400)
text(addComma(1234^3),WIDTH/2,350)
text(addComma(123456.1234),WIDTH/2,300)
text(addComma("11223344556677889900.12345678"),WIDTH/2,250)
end
function addComma(value)
loop=1
while loop>0 do
value,loop=string.gsub(value,"^(-?%d+)(%d%d%d)","%1,%2")
end
return value
end
Nice, very similar to the function I found for 30 Balls:
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
@JakAttak I’m surprised at how similar they are. And I want to say that I never looked at or loaded 30 balls. That’s a game and I don’t load them unless someone has a problem with it and I need to run it. Why did you use single ’ around %1,%2. I guess if I would have looked at 30 balls when you first posted it, that would have saved me some time. But then I needed some coding practice with gsub which is why I did that anyways. I have a hard time with the patterns, so I play around with it. A lot of times it’s hit and miss and a lot of reading until I get it to work.
Here’s another one from StackOverflow, that does without a loop
function addComma(number)
local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
-- reverse the int-string and append a comma to all blocks of 3 digits
int = int:reverse():gsub("(%d%d%d)", "%1,")
-- reverse the int-string back remove an optional comma and put the
-- optional minus and fractional part back
return minus .. int:reverse():gsub("^,", "") .. fraction
end
@Ignatz Now I’m going to have to get the book out again and see if I can figure out what’s happening there. The more of these I try to figure out, the more I understand the patterns.
This is really good, for my projects where I have a large number I just created a function to write the place value below the number (hundred million, hundred thousand, etc.) and it worked but it looked sloppy
@Ignatz I looked thru the code you showed and it turned out to be easy to understand. That doesn’t mean I would have been able to do it from scratch. In order to use the full potential of the functions that use patterns, you have to fully understand how to use the patterns. That’s where I still need a lot of practice, but looking at examples like you posted helps a lot.