JSFiddle - React, Tailwind, and code Playground
by dcdruck
HTML
<div id="output" style="border:1px solid gray;width:200px"></div>
JavaScript
var div = document.getElementById('output');
div.innerHTML += '<p>' + getFilesizeForHumans(2048,null,false) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(20000000000000000000,null,true) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(2048,'si',false) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(2000,'si',true) + '</p>';
function getFilesizeForHumans (bytes) {
var i, divisor = 1024, units = ['B','KB','MB','GB','TB','PB'];
for (i = 0; i < units.length; i++) {
computedDivisor = Math.pow(divisor,i);
if (bytes / computedDivisor < divisor || i+1 == units.length) {
return (Math.round((bytes / computedDivisor) * 100) / 100) + " " + units[i];
}
}
}