Read more photos in Lua

So, over the past hour or so, I've been having trouble with this feature to make the numbers easier to read. In its current state, the function works for numbers with a length of less than 6 characters.

1000,000
100,000

      

Please forgive me my amateur way with variables.

function neatnumber(number)
    local nslen = string.len(tostring(number))
    if nslen <= 3 then
        return number
    end
    local ns = tostring(number)
    local nslen = math.floor(string.len(ns) / 3)-1
    for i=1,nslen do
        neat = string.sub(ns,-#ns,#s-(3*i)) .. "," .. string.sub(ns,#ns-(2))
    end
    return neat
end

      

+3


source to share


2 answers


There may be a more elegant way, but you can use string.gsub

in a loop.

local function neatnumber(n)
    local s, i = string.format('%0.f', n)
    repeat
        s, i = s:gsub('^(%-?%d+)(%d%d%d)', '%1,%2')
    until i == 0
    return s
end

      

The gsub pattern scans the string for a number (which can be negative), looking for consecutive decimal digits and capturing the entire sequence up to the last three digits. The second capture gets the last three digits. The wildcard concatenates the two captures and adds a comma between them.



This should work for any integer (positive or negative):

neatnumber(2^53)   -->  9,007,199,254,740,992
neatnumber(-2^53)  --> -9,007,199,254,740,992

      

+2


source


Here's a similar solution also uses string.gsub

, but without loops:



function neatnumber(n, delim)
    delim = delim or ','
    n = ('%0.f'):format(n)

    local groups = math.ceil(#n / 3) - 1
    n = n:reverse()
    n = n:gsub('(%d%d%d)', '%1' .. delim, groups)
    return n:reverse()
end

      

+2


source







All Articles