Ok, So basically, ive created cookie clicker like game , and I want the number to look like this : (e.g)
55,555,555 not like this : 5555555, so its easier to read. Heres what I got so far:
local sv = tostring(integer.Value) -- the number of cookies (example) that have been converted local string = sv local newstring = '' -- I don't know what I need to put here for i = 1,#string do if i%4 == 0 then newstring = (newstring..','..string[i]) else newstring = (newstring..string[i]) end end
PM me @ Bubbles5610 on roblox if you have any further questions or you want my testing place uncopylocked to look at the allocated variables .
Thanks :)
Since string.format doesn't have a format for that you will have to create your own.
function addComas(str) return #str % 3 == 0 and str:reverse():gsub("(%d%d%d)", "%1,"):reverse():sub(2) or str:reverse():gsub("(%d%d%d)", "%1,"):reverse() end print(addComas("250000000")) print(addComas("25000000"))
250,000,00
25,000,000
Explaining the code:
We are using three functions
string.reverse(str): It reverses str, so "Hi" becomes "iH"
string.sub(str, start, [end]): Where end is optional, it returns the substring from start to end. So string.sub("Hello", 2) returns "ello"
string.gsub(str, pattern, replace, [n]): This is quite complicated, it searches str for matches using pattern and then replaces it with replace, n is optional and it's the number of maximum substitutions it is allowed to make. So string.gsub("Hello", "llo", "lp") returns "Help"
Then we put everything together:
Let's take "250000" for example, if we use string.gsub("25000", "(%d%d%d)", "%1,") it will return 250,00 because it searches the string from left to right, so we have to reverse it.
string.reverse("25000"):gsub("(%d%d%d)", "%1,") will return "000,52" so we reverse it again to revert the process. string.reverse("25000"):gsub("(%d%d%d)", "%1,") :reverse() and that's it.
There is a problem if the string length if multiple of three, like "250" because it will become ",250" so in order to fix that we just check if it's multiple of 3 and if it is we remove the first character, that's the comma.
EDIT: There was a bug in the code where "250000" would become ",250,000" that's is if the number of digits was multiple of three, so if it is then we just remove that.
Explaining lombardo's code:
function addComas(str) return #str > 3 and str:reverse():gsub("(%d%d%d)", "%1,"):reverse() or str end print(addComas("25000000"))
Basically, return #str > 3
and the entire rest of line 2 actually just counts how many characters there are in a string and every 3 lines a comma is added. The and str:reverse()
bit just makes it count in reverse since that's how you would know where you would put the comma in real life.
If I'm wrong, I'm sorry. ;p
I'm not a great scripter but I can read scripts and know what they do.
Locked by User#24403
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?