utils: Add an utility function to format bytes.

This commit is contained in:
Damir Jelić 2019-11-26 13:39:45 +01:00
parent 928bb69b11
commit 2fe3603737

View file

@ -30,6 +30,22 @@ export function formatCount(count) {
return (count / 1000000000).toFixed(1) + "B"; // 10B is enough for anyone, right? :S
}
/**
* format a size in bytes into a human readable form
* e.g: 1024 -> 1.00 KB
*/
export function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
/**
* format a key into groups of 4 characters, for easier visual inspection
*