我想将数字格式化为1,2341,234,432123,456,789,您明白了。我尝试这样做,如下所示:

function reformatint(i)
    local length = string.len(i)
    for v = 1, math.floor(length/3) do
        for k = 1, 3 do
            newint = string.sub(mystring, -k*v)
        end
        newint = ','..newint
    end
    return newint
end
如您所见,尝试失败,我的问题是我无法弄清楚错误是什么,因为我正在其中运行的程序拒绝向我报告错误。

最佳答案

这是一个考虑负数和小数部分的函数:

function format_int(number)

  local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')

  -- reverse the int-string and append a comma to all blocks of 3 digits
  int = int:reverse():gsub("(%d%d%d)", "%1,")

  -- reverse the int-string back remove an optional comma and put the
  -- optional minus and fractional part back
  return minus .. int:reverse():gsub("^,", "") .. fraction
end

assert(format_int(1234)              == '1,234')
assert(format_int(1234567)           == '1,234,567')
assert(format_int(123456789)         == '123,456,789')
assert(format_int(123456789.1234)    == '123,456,789.1234')
assert(format_int(-123456789.)       == '-123,456,789')
assert(format_int(-123456789.1234)   == '-123,456,789.1234')
assert(format_int('-123456789.1234') == '-123,456,789.1234')

print('All tests passed!')

关于lua - 在Lua中格式化整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10989788/

10-13 08:05