问题描述
我想将人类可读的大小(例如“10Mi”)转换回实数大小
我写了以下内容,但我似乎在转换中遗漏了一些东西
function humanFileSizetoSize (sizeString) {
const units = ['Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi'];
const unitString = units.find(unit => sizeString.includes(unit));
const power = units.indexOf(unitString) + 1;
const size = parseFloat(sizeString.slice(0,sizeString.indexOf(unitString)))
return parseInt(size * (1024**power));
}
console.log(humanFileSizetoSize("10Mi"))
console.log(humanFileSizetoSize("1.5Mi"))
解决方法
假设 1 MiB 等于 1048576 字节,似乎可以按预期工作。
虽然可以缩短,并且无需库即可完成
const units = [,'Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi'];
const re = /(\d+(?:\.\d+)?)([KMGTPEZYi]{2})/g;
const humanFileSizeToSize = sizeString => {
const [[_,size,unit]] = sizeString.matchAll(re);
const power = units.indexOf(unit)
return parseInt(size * (1024 ** power));
}
console.log(humanFileSizeToSize("1Ki"))
console.log(humanFileSizeToSize("1Mi"))
console.log(humanFileSizeToSize("1.5Mi"))
console.log(humanFileSizeToSize("10Mi"))
console.log(humanFileSizeToSize("1Gi"))