-
-
Save zentala/1e6f72438796d74531803cc3833c039c to your computer and use it in GitHub Desktop.
| function formatBytes(bytes,decimals) { | |
| if(bytes == 0) return '0 Bytes'; | |
| var k = 1024, | |
| dm = decimals || 2, | |
| sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], | |
| i = Math.floor(Math.log(bytes) / Math.log(k)); | |
| return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; | |
| } | |
| // Usage: | |
| // formatBytes(bytes,decimals) | |
| formatBytes(1024); // 1 KB | |
| formatBytes('1024'); // 1 KB | |
| formatBytes(1234); // 1.21 KB | |
| formatBytes(1234, 3); // 1.205 KB |
Clever
Thank you for sharing!
Absolutely cool snippet
Thank you! Helped a lot.
Awesome snippet. Thanks!
This helped a lot! Thank you
Nice concept. I've forked it to support IEC units as well
Very nice, gonna use myself. Thanks, I did make some minor changes though.
export function formatBytes(bytes, dm = 2) {
if (bytes == 0) return '0 Bytes';
var k = 1024,
sizes = [`${bytes <= 1 ? "Byte" : "Bytes"}`, 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}```
Awesome!
Perfect! Exactly what I was looking for. π
Great work, and thanks!
thank you π
this is my typescript version with minor changes
function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return "0 Bytes";
const k = 1024;
const dm = decimals || 2;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${Number.parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
}If you find yourself tweaking this snippet frequently, smart-unit might be worth a look β it handles this out of the box with configurable decimal places, TypeScript support, and bidirectional format/parse:
const size = new SmartUnit(['B', 'KB', 'MB', 'GB', 'TB'], { baseDigit: 1024 });
size.format(1234); // "1.21KB"
size.parse('1.5GB'); // 1610612736And bytes formatting is just one use case β the same API works for any unit system with variable ratios, like time, length, frequency, or anything custom:
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h']);
time.format(5400000); // "1.5h"
WOW NICE!!!!