How to format numbers in Lua?

5

I would like to know how to format the variable:

local n = 100000000

To return like this:

100.000.000

Separated by dots, does anyone know how to do it?

    
asked by anonymous 04.06.2015 / 04:46

3 answers

3
function dot_string(s)
    -- não precisamos de pontinhos para números até 999
    if s:len() <= 3 then
        return s
    end 

    -- senão, colocamos o pontinho no último grupo de 3 e repetimos o processo para o que sobrou
    return dot_string(s:sub(1, -4)) .. "." .. s:sub(-3)
end 

function dot_number(n)
    -- TODO: n < 0
    -- TODO: n != int(n)
    -- TODO: n grande
    return dot_string(tostring(n))
end

If on is negative, fractional or giant, tostring () will do lame, but otherwise the function does what you asked for (at least the first two cases are easy to handle with if s in dot_number before call the dot_string).

Example:

print(dot_number(0))
print(dot_number(10))
print(dot_number(210))
print(dot_number(3210))
print(dot_number(43210))
print(dot_number(543210))
print(dot_number(6543210))
print(dot_number(10000000000000))

print()
-- …alguns casos que não funcionam…
print(dot_number(-123))
print(dot_number(12.5))
print(dot_number(100000000000000))

Output:

0
10
210
3.210
43.210
543.210
6.543.210
10.000.000.000.000

-.123
1.2.5
1e.+14
    
04.06.2015 / 12:00
4

The form proposed by page Formatting Numbers - lua-users.org is to use the string.gsub function as follows:

function formatarNumero(valor)
  local formatado = valor
  while true do  
                                          -- O "." entre "%1" e "%2" é o separador
    formatado, n = string.gsub(formatado, "^(-?%d+)(%d%d%d)", '%1.%2') 
    if ( n ==0 ) then
      break
    end
  end
  return formatado
end

The expression

04.06.2015 / 13:03
0
function func(number)
    local number = number
    local decimal = number - math.floor(number)
    decimal = tonumber(tostring(decimal):sub(3, string.len(decimal)))
    number = tostring(math.floor(number)):reverse()
    for _ = 3, #number, 4 do
            number = number:sub(1, _) .. "." .. number:sub(_ + 1, #number)
    end
    return number:reverse() .. (decimal and "," .. decimal or "")
end
    
27.06.2015 / 03:59