FHUG Home
Knowledge Base Home
FHUG Downloads
Contributing Your Knowledge
How To Guides:
Cross References:
Takes a number and returns a number formatted with the number of decimals passed as the second parameter and using commas for the thousands.
e.g
Requires: None
function formatNumber(number,decimals) local function round(num, idp) local mult = 10^(idp or 0) if num >= 0 then return math.floor(num * mult + 0.5) / mult else return math.ceil(num * mult - 0.5) / mult end end decimals = decimals or 0 number = round(number,decimals) local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)') if fraction == '' and decimals > 0 then fraction = '.' end -- 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 padding if required return minus .. int:reverse():gsub("^,", "") .. string.sub(fraction .. string.rep('0',decimals),1,decimals + 1) end -- Usage print(formatNumber(-1123235.49,2)) -- -1,123,235.49 print(formatNumber(-1123235.49,0)) -- -1,123,235
Section plugins:code_snippets