什么是javascript中将字节转换为可读格式的最优雅方式

时间:2012-05-17 17:34:40

标签: javascript

我在stackoverflow上找到了一个非常优雅的'humanize'转换器,它没有使用任何循环。

是否可以使用javascript执行相同的操作? (例如1024字节=> 1 kb)?

听起来很简单,我已经做了很多搜索

如果你想知道:Java Version

2 个答案:

答案 0 :(得分:6)

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" */

请注意,Java版本结果表显示的错误为7.1 KB而不是7.1 MB

答案 1 :(得分:0)

现在有一些非常好用于JS的Humanize库,我建议你看一下:

HubSpot/Humanize Plus

如果您想看看,还有https://github.com/taijinlee/humanize