Ferdi
Ferdi

Reputation: 33

Make easier to read numbers in Lua

So for the past hour or so I've been having issues with this function to make numbers easier to read. In its current state the function does work for numbers with a length below 6 characters like so.

1000,000
100,000

Please forgive my amateur ways 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

Upvotes: 3

Views: 374

Answers (2)

greatwolf
greatwolf

Reputation: 20838

Here's a similar solution also using 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

Upvotes: 2

Adam
Adam

Reputation: 3103

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 might be negative) looking for consecutive decimal digits, and capturing the whole sequence up to the last three digits. A second capture gets the last three digits. The substitution concatenates the two captures and adds a comma between.

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

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

Upvotes: 2

Related Questions