Guest User

Unminified Number Formatter (JS)

a guest
Oct 23rd, 2016
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var n = { // Object to store everything in, this isn't required but helps it take up less space
  2.     log: Math.log(10), // Math.log(10) is stored here to prevent the need to recalculate it multiple times
  3.     array: ["", "k", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc", "UnD", "DuD", "TrD", "QaD", "QiD", "SeD", "SpD", "OcD", "NoD", "Vi", "UnV"], // This array can go on as long as you need, it's the abbreviations for large numbers
  4.     floor: function(a) { // This function is Math.floor() only with support for floating points and negative numbers
  5.         // a (required) = number to round down to whole numbers
  6.         if(Math.abs(Math.abs(a) - Math.abs(Math.floor(a))) >= 0.999999991) {
  7.             if(a >= 0) {
  8.                 return Math.ceil(a);
  9.             }else{
  10.                 return Math.floor(a);
  11.             }
  12.         }else{
  13.             if(a >= 0) {
  14.                 return Math.floor(a);
  15.             }else{
  16.                 return Math.ceil(a);
  17.             }
  18.         }
  19.     },
  20.     format: function(a, b) { // This is the actual number formatting function, also supports floating points and negative numbers.  If number is greater than array of long number endings supports than "Infinite" is returned.
  21.         // a (required) = number to format
  22.         // b (optional) = number of decimal places to use for numbers under 1000 (ones without letter endings)
  23.         var l, p, r;
  24.         if(n.floor(Math.log(Math.abs(a)) / n.log) <= 0) {
  25.             l = 0;
  26.         }else{
  27.             l = n.floor(Math.log(Math.abs(a)) / n.log;
  28.         }
  29.         if(l % 3 === 0) {
  30.             p = 2;
  31.         }else if((l - 1) % 3 === 0) {
  32.             p = 1;
  33.         }else{
  34.             p = 0;
  35.         }
  36.         if(Math.abs(a) < 1000) {
  37.             if(typeof b === "number") {
  38.                 r = a.toFixed(b);
  39.             }else{
  40.                 r = n.floor(a);
  41.             }
  42.         }else{
  43.             r = n.floor(a / (Math.pow(10, n.floor(l / 3) * 3 - p))) / Math.pow(10, p);
  44.         }
  45.         if(typeof n.array[n.floor(l / 3)] === "string") {
  46.             return r + n.array[n.floor(l / 3)];
  47.         }else{
  48.             return "Infinite";
  49.         }
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment