Skip to content

Instantly share code, notes, and snippets.

@rmorlok
Forked from lanqy/bytesToSize.js
Last active July 8, 2022 17:32
Show Gist options
  • Save rmorlok/9b5abe7321de6d637a4c80ecc6e7d364 to your computer and use it in GitHub Desktop.
Save rmorlok/9b5abe7321de6d637a4c80ecc6e7d364 to your computer and use it in GitHub Desktop.
JavaScript To Convert Bytes To MB, KB, Etc
export function bytesToSize(bytes: number): string {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return 'n/a';
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), sizes.length - 1);
if (i === 0) return `${bytes} ${sizes[i]}`;
return `${(bytes / (1024 ** i)).toFixed(1)} ${sizes[i]}`;
}
// Jest spec
describe('bytesToSize', () => {
test.each([
[0, 'n/a'],
[1, '1 Bytes'],
[2000, '2.0 KB'],
[30000, '29.3 KB'],
[400000, '390.6 KB'],
[5000000, '4.8 MB'],
[60000000, '57.2 MB'],
[700000000, '667.6 MB'],
[8000000000, '7.5 GB'],
[90000000000, '83.8 GB'],
[100000000000, '93.1 GB'],
[1100000000000, '1.0 TB'],
[12000000000000, '10.9 TB'],
[130000000000000, '118.2 TB'],
[1400000000000000, '1273.3 TB'],
[15000000000000000, '13642.4 TB'],
])('.bytesToSize(%p)', (
val: number,
expected: string,
) => {
expect(
bytesToSize(val),
).toBe(expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment