Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

formatting - Format integer in Lua

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

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

As you can see, a failed attempt, my problem is that I can't figure out what the error is because the program I am running this in refuses to report an error back to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a function that takes negative numbers, and fractional parts into account:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...