int - Lua - Format integer -


i'd format number follows "1,234" or "1,234,432" or "123,456,789", idea. tried doing follows;

function reformatint(i)     local length = string.len(i)     v = 1, math.floor(length/3)         k = 1, 3             newint = string.sub(mystring, -k*v)         end         newint = ','..newint     end     return newint end 

as can see have failed attempt, problem cannot work out what's @ fault program running in, refuses post error me.

here's function takes negative numbers, , fractional parts account:

function format_int(number)    local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')    -- reverse int-string , append comma blocks of 3 digits   int = int:reverse():gsub("(%d%d%d)", "%1,")    -- reverse int-string remove optional comma , put    -- optional minus , fractional part   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!') 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -