Advertisement
Guest User

Untitled

a guest
Jan 19th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. #!/usr/bin/env lua
  2.  
  3. local prefixes = {
  4. [0] = "",
  5. [3] = "K",
  6. [6] = "M",
  7. [9] = "G",
  8. [12] = "T",
  9. [15] = "P",
  10. };
  11.  
  12. function round(n)
  13. return tonumber(string.format("%.1f", n));
  14. end
  15.  
  16. function divideNumber(n)
  17. local n = tonumber(n);
  18.  
  19. if not n then error("Not a number", 2) end
  20.  
  21. -- Get the log
  22. local l = ((n == 0) and 0) or math.floor(math.log(n, 10));
  23. -- Make it a multiple of 3, rounding down
  24. l = l - (l % 3);
  25.  
  26. return round(n / math.pow(10, l))..prefixes[l];
  27. end
  28.  
  29. for input in io.lines() do
  30. io.write(string.gsub(input, "%d+", divideNumber).."\n");
  31. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement