(example 10000000 to 10,000,000) this is my script, please help me
number = 1000000
print(string.sub(number,0,2) .. "," .. string.sub(number,2,(string.len(number)-3)) .. "," .. string.sub(number,3,string.len(number)-2))
(example 10000000 to 10,000,000) this is my script, please help me
number = 1000000
print(string.sub(number,0,2) .. "," .. string.sub(number,2,(string.len(number)-3)) .. "," .. string.sub(number,3,string.len(number)-2))
Your code itself works fine, if you wanted to change the number itself to include the commas, you can simply redefine the variable
local number = 1000000
local str1 = string.sub(number, 0, 2)
local str2 = string.sub(number, 2, (string.len(number) - 3))
local str3 = string.sub(number, 3, (string.len(number) - 2))
number = (str1..","..str2.. ","..str3)
If you want to make it so any number is given commas, you can do the following:
Local Variables for length / making a table:
string.len() tells us the amount of characters in the string
the "newlen" variable adds on a length to match with the amount of commas we will be adding.
local array = {}
local number = 100
local len = string.len(number)
local newlen = (math.floor((len + math.floor(len / 4)) / 4) * 4)
string.reverse() flips the number string around so we can later check every 4 values to add a comma (if the number is longer than 4 characters).
local rev = string.reverse(number)
The array is used to separate the characters of the number into individual strings.
for str = 1, len do
local count = #array + 1
table.insert(array, count, string.sub(rev, count, count))
end
Next we add commas every 4 index values (unless it is below 4 as per the newlen variable) using table.insert()
for comma = 4, newlen, 4 do
table.insert(array, comma, ",")
end
After adding commas to the table, we iterate back over the array to create a new string.
local oldstring = ""
for val = 1, #array, 1 do
local newstring = array[val]
oldstring = tostring(oldstring..""..newstring)
end
Finalized Script
local array = {}
local number = 100
local len = string.len(number)
local newlen = (math.floor((len + math.floor(len / 4)) / 4) * 4)
local rev = string.reverse(number)
for str = 1, len do
local count = #array + 1
table.insert(array, count, string.sub(rev, count, count))
end
for comma = 4, newlen, 4 do
table.insert(array, comma, ",")
end
local oldstring = ""
for val = 1, #array, 1 do
local newstring = array[val]
oldstring = tostring(oldstring..""..newstring)
end
number = string.reverse(oldstring)
print(number)
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
lua-users.org/wiki/FormattingNumbers