Advertisement
Guest User

Lua | Number Formatting

a guest
Feb 13th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.50 KB | None | 0 0
  1. --[[
  2.     turn numbers like 1216112.5161 into 1,216,112.5161
  3. ]]
  4.  
  5. function number_format(num)
  6.     local neg = num < 0
  7.     num = math.abs(num)
  8.     local size = math.floor(math.log10(num)) + 1
  9.     local offset = size % 3
  10.     local str = ""
  11.    
  12.     local s, e = tostring(num):find("%.")
  13.     for i = #tostring(num), 1, -1 do
  14.         if math.abs(i % 3 - offset) == 0 and i ~= size and ((s ~= nil and i < s) or s == nil) then
  15.             str = "," .. str
  16.         end
  17.         str = tostring(num):sub(i,i) .. str
  18.     end
  19.    
  20.     return ((neg and "-") or "") .. str
  21. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement