bytes 转KB、MB、GM记录
最近做项目,要求把KB、MB、GB等格式的转成bytes
想着手写一个挺麻烦,也没什么思路,就百度了一下
直接上代码
摘抄大神方案
byteConvert (bytes) {
if (isNaN(bytes)) {
return '';
}
var symbols = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var exp = Math.floor(Math.log(bytes)/Math.log(2));
if (exp < 1) {
exp = 0;
}
var i = Math.floor(exp / 10);
bytes = bytes / Math.pow(2, 10 * i);
if (bytes.toString().length > bytes.toFixed(2).toString().length) {
bytes = bytes.toFixed(2);
}
return bytes + ' ' + symbols[i];
}
- 这不是我想要的
- 不过仔细看了代码,原来反转一下,就特别简单了
请看代码
getBytes(bytes, unit) {
const i = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'].indexOf(unit);
return Math.pow(2, 10 * i) * bytes;
}
仅此两句代码,就搞定了,膜拜大神