Created
December 15, 2012 05:25
-
-
Save jasonbradley/4291511 to your computer and use it in GitHub Desktop.
Format a number in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Util.format_num = function(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(Util.round(amount,decimal)) | |
famount = math.floor(famount) | |
remain = Util.round(math.abs(amount) - famount, decimal) | |
-- comma to separate the thousands | |
formatted = Util.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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment