Lua - Format integer

后端 未结 4 1424
天涯浪人
天涯浪人 2020-12-11 18:27

i\'d like to format a number to look as follows \"1,234\" or \"1,234,432\" or \"123,456,789\", you get the idea. I tried doing this as follows;

function ref         


        
4条回答
  •  误落风尘
    2020-12-11 19:05

    You can do without loops:

    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")
    

    The second gsub is needed to avoid -,100 being generated.

提交回复
热议问题