当前位置 : 主页 > 网络编程 > lua >

Lua – 格式整数

来源:互联网 收集:自由互联 发布时间:2021-06-23
我想格式化一个数字看起来如下“1,234”或“1,234,432”或“123,456,789”,你明白了.我尝试这样做如下; function reformatint(i) local length = string.len(i) for v = 1, math.floor(length/3) do for k = 1, 3 do newin
我想格式化一个数字看起来如下“1,234”或“1,234,432”或“123,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!')
网友评论