Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua中的整数格式_Lua_Formatting_Integer - Fatal编程技术网

Lua中的整数格式

Lua中的整数格式,lua,formatting,integer,Lua,Formatting,Integer,我想把一个数字格式化成1234或1234432或123456789,你明白了。我试着这样做: 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 = ','..n

我想把一个数字格式化成
1234
1234432
123456789
,你明白了。我试着这样做:

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

正如您所看到的,一次失败的尝试,我的问题是我无法找出错误是什么,因为我正在运行的程序拒绝向我报告错误。

好吧,让我们从头开始。首先,它失败是因为您有一个引用错误:

    ...
        for k = 1, 3 do
            newint = string.sub(mystring, -k*v) -- What is 'mystring'?
        end
    ...
很可能您希望
i
在那里,而不是
mystring

其次,虽然用
i
替换
mystring
将修复错误,但它仍然无法正常工作

> =reformatint(100)
,100
> =reformatint(1)
,000
这显然是不对的。看起来您要做的是遍历字符串,并使用添加的逗号构建新字符串。但是有几个问题

function reformatint(i)
    local length = string.len(i)
    for v = 1, math.floor(length/3) do
        for k = 1, 3 do -- What is this inner loop for?
            newint = string.sub(mystring, -k*v) -- This chops off the end of
                                                -- your string only
        end
        newint = ','..newint -- This will make your result have a ',' at
                             -- the beginning, no matter what
    end
    return newint
end
通过一些返工,您可以得到一个有效的函数

function reformatint(integer)
    for i = 1, math.floor((string.len(integer)-1) / 3) do
        integer = string.sub(integer, 1, -3*i-i) ..
                  ',' ..
                  string.sub(integer, -3*i-i+1)
    end
    return integer
end
上述功能似乎工作正常。然而,这是相当复杂的。。。可能想让它更具可读性

作为旁注,a查找已为此创建的函数:

function comma_value(amount)
  local formatted = amount
  while true do  
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
    if (k==0) then
      break
    end
  end
  return formatted
end

您可以不使用循环:

function numWithCommas(n)
  return tostring(math.floor(n)):reverse():gsub("(%d%d%d)","%1,")
                                :gsub(",(%-?)$","%1"):reverse()
end

assert(numWithCommas(100000) == "100,000")
assert(numWithCommas(100) == "100")
assert(numWithCommas(-100000) == "-100,000")
assert(numWithCommas(10000000) == "10,000,000")
assert(numWithCommas(10000000.00) == "10,000,000")

需要第二个gsub来避免生成-,100。

这里有一个函数,它考虑了负数和小数部分:

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!')

我记得我在。。。让我找找看

!

这将适用于正整数:

function reformatInt(i)
  return tostring(i):reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")
end

在上面的链接上,您可以阅读有关实现的详细信息。

uff,我从一个网页上撕下了包含mystring的部分,显然我太傻了,忘了把它换掉。事实证明,我的谷歌搜索结果非常不正确。我想感谢您,我将更深入地研究string.sub()是如何操作的。我希望我到目前为止的愚蠢行为至少能让我学到一些东西。@Hultin:没必要瞧不起你自己——我们都会犯错误,而且有时是愚蠢的错误。这就是我们学习的方式。是的,理解
string.sub()
是一项值得努力的工作——它实际上与其他语言中的子字符串函数略有不同。另外,欢迎来到StackOverflow!如果包含小数(不是要求),为什么不包含逗号分隔?