FANDOM


---============================================================
-- Format a number
-- Usage: formatNum( amount, decimal, prefix, negPrefix )
--   amount: the number to be formatted
--   decimal: the number of decimal places to round to (default: 0)
--   prefix: the symbol to prefix the number with ("$", etc.)
--   negPrefix: the negative sign ("-" for normal, "()" for parentheses, etc.)
 
local p = {}
 
---============================================================
-- add comma to separate thousands
-- 
local function commaValue( amount )
   local formatted = amount
   while true do  
      formatted, k = string.gsub( formatted, "^(-?%d+)(%d%d%d)", '%1,%2' )
 
      if ( k == 0 ) then
         break
      end
   end
 
   return formatted
end
 
---============================================================
-- rounds a number to the nearest decimal places
--
local function round( val, decimal )
   if ( decimal ) then
      return math.floor( ( val * 10 ^ decimal ) + 0.5 ) / ( 10 ^ decimal )
   else
      return math.floor( val + 0.5 )
   end
end
 
--===================================================================
-- given a numeric value formats output with comma to separate thousands
-- and rounded to given decimal places
--
--
function p.formatNum( amount, decimal, prefix, negPrefix )
   local formatted, famount, remain
 
   if not tonumber( amount ) then
      return amount
   end
 
   amount    = tonumber( amount )
   decimal   = decimal or 0     -- default 0 decimal places
   negPrefix = negPrefix or "-" -- default negative sign
 
   famount = math.abs( round( amount, decimal ) )
   famount = math.floor( famount )
 
   remain = round( math.abs( amount ) - famount, decimal )
 
   -- comma to separate the thousands
   formatted = commaValue( famount )
 
   -- attach the decimal portion
   if ( decimal > 0 ) then
      remain = string.sub( tostring( remain ), 3 )
      formatted = formatted .. "." .. remain ..
         string.rep( "0", decimal - string.len( remain ) )
   end
 
   -- attach prefix string e.g '$' 
   formatted = ( prefix or "" ) .. formatted 
 
   -- if value is negative then format accordingly
   if ( amount < 0)  then
      if ( negPrefix == "()" ) then
         formatted = "(" .. formatted .. ")"
      else
         formatted = negPrefix .. formatted 
      end
   end
 
   return formatted
end
 
function p.main(frame)
   local amount    = tonumber( frame.args['amount'] )
   local decimal   = tonumber( frame.args['decimal'] )
   local prefix    = frame.args['prefix']
   local negPrefix = frame.args['negPrefix']
 
   return p.formatNum( amount, decimal, prefix, negPrefix )
end
 
return p

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.