js number to units

Solutions on MaxInterview for js number to units by the best coders in the world

showing results for - "js number to units"
Sara
28 Jul 2017
1function nFormatter(num, digits) {
2  var si = [
3    { value: 1, symbol: "" },
4    { value: 1E3, symbol: "k" },
5    { value: 1E6, symbol: "M" },
6    { value: 1E9, symbol: "G" },
7    { value: 1E12, symbol: "T" },
8    { value: 1E15, symbol: "P" },
9    { value: 1E18, symbol: "E" }
10  ];
11  var rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
12  var i;
13  for (i = si.length - 1; i > 0; i--) {
14    if (num >= si[i].value) {
15      break;
16    }
17  }
18  return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
19}