Format Number (code snippet)

Description

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.

  • Two Decimals 1,789.00
  • Zero Decimals 123,456

Requires: None

Code

FormatNumber.fh_lua
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