Ver*_*Lom 9 javascript function human-readable
我有以字节为单位的数据.我需要在图表上绘制这些值作为人类可读的标签(如2.5KB,14MB等),并需要帮助功能(输入数据 - 实际值,输出 - 人类可读的字符串).
我做了这样的功能,但我想要更优雅的实现
function tickFormatter(value, type) {
var suffix = (type == "bytes") ? ['B', 'KB', 'MB', 'GB'] : ['', 'K', 'M', 'G']
if(value > (1024 * 1024 * 1024 * 1024)) {
return (value / (1024 * 1024 * 1024 * 1024)).toFixed(2) + suffix[3]
} else if(value > (1024 * 1024 * 1024)) {
return (value / (1024 * 1024 * 1024)).toFixed(2) + suffix[2]
} else if (value > (1024 * 1024)) {
return (value / (1024 * 1024)).toFixed(2) + suffix[1]
} else {
return value.toFixed(2) + suffix[0]
}
}
Run Code Online (Sandbox Code Playgroud)
mic*_*red 26
我喜欢这个实现:清晰紧凑:
function readablizeBytes(bytes) {
var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
}
Run Code Online (Sandbox Code Playgroud)
用法:
readablizeBytes(10000000)
"9.54 MB"
Run Code Online (Sandbox Code Playgroud)
我不相信这一点.
Ami*_*mir 17
这就是我使用的.它向上舍入到最近的单位,因此1000是"0.98KB"如果你不想这样,那么将第一个Math.round更改为一个楼层.
var SizePrefixes = ' KMGTPEZYXWVU';
function GetHumanSize(size) {
if(size <= 0) return '0';
var t2 = Math.min(Math.round(Math.log(size)/Math.log(1024)), 12);
return (Math.round(size * 100 / Math.pow(1024, t2)) / 100) +
SizePrefixes.charAt(t2).replace(' ', '') + 'B';
}
Run Code Online (Sandbox Code Playgroud)