Format Number -- output with commas and rounded to given decimal places

Example usage: amount = 1333444.1 print(format_num(amount,2)) print(format_num(amount,-2,"US$")) amount = -22333444.5634 print(format_num(amount,2,"$")) print(format_num(amount,2,"$","()")) print(format_num(amount,3,"$","NEG "))
Send Snippet To: Save this snippet to Code Collector Pro -- view all roger's snippets
language: Other
license: Other

Code for Snippet:

                
-- given a numeric value formats output with comma to separate thousands
-- and rounded to given decimal places
--
--
function format_num(amount, decimal, prefix, neg_prefix)
  local str_amount,  formatted, famount, remain
 
  decimal = decimal or 2  -- default 2 decimal places
  neg_prefix = neg_prefix 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 = comma_value(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 (neg_prefix=="()") then
      formatted = "("..formatted ..")"
    else
      formatted = neg_prefix .. formatted 
    end
  end
 
  return formatted
end
comments powered by Disqus

Info

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 8
Date Added: 2018-01-09 04:48:14
Last Modified: 2018-01-10 09:54:13

Web Analytics