Prijeđi na sadržaj

Modul:NumberFormatting

Izvor: Wikipedija
local NumberFormatting = { };

function NumberFormatting.format(number, decimal, decimal_mark, thousands_separator, neg_prefix)
  number = tonumber(number)
  local str_amount, formatted, famount, remain

  decimal = decimal or 2
  decimal_mark = decimal_mark or ","
  thousands_separator = thousands_separator or " "
  neg_prefix = neg_prefix or "-"

  famount = math.abs(NumberFormatting.round(number,decimal))
  famount = math.floor(famount)
  remain = NumberFormatting.round(math.abs(number) - famount, decimal)
  formatted = NumberFormatting.separateThousands(famount,thousands_separator)

  if (decimal > 0) then
    remain = string.sub(tostring(remain),3)
    formatted = formatted .. decimal_mark .. remain ..
                string.rep("0", decimal - string.len(remain))
  end

  if (number<0) then
    if (neg_prefix=="()") then
      formatted = "("..formatted ..")"
    else
      formatted = neg_prefix .. formatted 
    end
  end
  return formatted
end

function NumberFormatting.round(number, decimal)
  number = tonumber(number)
  if (decimal) then
    return math.floor( (number * 10^decimal) + 0.5) / (10^decimal)
  else
    return math.floor(number+0.5)
  end
end

function NumberFormatting.separateThousands(number, thousands_separator)
  local formatted = number
  while true do  
    formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1'..thousands_separator..'%2')
    if (k==0) then
      break
    end
  end
  return formatted
end

return NumberFormatting;