4

I found a very elegant 'humanize' converter for Java on stackoverflow which didn't use any loops.

Is it possible to do the same with javascript? (e.g 1024 bytes => 1 kb)?

As simple as it sounds I have done quite a search for it

Incase you're wondering : Java Version

Community
  • 1
  • 1
Tarang
  • 75,157
  • 39
  • 215
  • 276
  • Java or javascript? Also, what is your question? – jrummell May 17 '12 at 17:35
  • 1
    Javascript =). The version I found here was for java – Tarang May 17 '12 at 17:36
  • Here's a function to do it: http://codeaid.net/javascript/convert-size-in-bytes-to-human-readable-format-(javascript) – Jamey May 17 '12 at 17:38
  • Could you paste the link again I get an 'Article not found' when I click that – Tarang May 17 '12 at 17:39
  • Copy paste of link doesn't work, so first hit on this google search - https://www.google.com/webhp?rlz=1C1CHFX_enUS460US460&sourceid=chrome-instant&ix=h9&ie=UTF-8#hl=en&rlz=1C1CHFX_enUS460US460&sclient=psy-ab&q=codeaid.net%20convert%20size%20in%20bytes%20to%20human%20readable%20format%20javascript&oq=&aq=&aqi=&aql=&gs_l=&pbx=1&fp=95c2cca83de3aed3&ix=h9&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&biw=1366&bih=653 – mrtsherman May 17 '12 at 17:46
  • I found it.. they have a really nice elegant one in the comments near the bottom – Tarang May 17 '12 at 17:49

2 Answers2

5
function byteCount (bytes, unit) {
  if (bytes < (unit = unit || 1000)) 
    return bytes + " B";
  var exp = Math.floor (Math.log (bytes) / Math.log (unit));
  var pre = ' ' +(unit === 1000 ? "kMGTPE" : "KMGTPE").charAt (exp - 1) + (unit === 1000 ? "" : "i") + 'B';
    return (bytes / Math.pow (unit, exp)).toFixed (1) + pre;
}

[ 0, 27, 999, 1000, 1023, 1024, 1728, 110592, 7077888, 
  452984832, 28991029248, 1855425871872, 9223372036854775807].forEach (
    function (v) { console.log (v, byteCount (v), byteCount (v, 1024)); });

/* Displays :    
0 "0 B" "0 B"
27 "27 B" "27 B"
999 "999 B" "999 B"
1000 "1.0 kB" "1000 B"
1023 "1.0 kB" "1023 B"
1024 "1.0 kB" "1.0 KiB"
1728 "1.7 kB" "1.7 KiB"
110592 "110.6 kB" "108.0 KiB"
7077888 "7.1 MB" "6.8 MiB"
452984832 "453.0 MB" "432.0 MiB"
28991029248 "29.0 GB" "27.0 GiB"
1855425871872 "1.9 TB" "1.7 TiB"
9223372036854776000 "9.2 EB" "8.0 EiB" */

Note the Java version results table has an error displaying 7.1 KB instead of 7.1 MB

HBP
  • 15,685
  • 6
  • 28
  • 34
0

There's now a couple of pretty nice Humanize libraries for JS, I'd recommend you have a look at:

HubSpot/Humanize Plus

There's also https://github.com/taijinlee/humanize if you'd like to take a look.

wizztjh
  • 6,979
  • 6
  • 58
  • 92