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>' + getBytesFromHumanFilesize(getFilesizeForHumans(2048,null,false)) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(2000000,null,true) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(2048,'si',false) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(2000,'si',true) + '</p>';
div.innerHTML += '<p>' + getFilesizeForHumans(94239984494238919423423,'si',true) + '</p>';
function getFilesizeForHumans (bytes,mode,iunits,forceunit,places) {
var divisor = mode==='si' ? 1000 : 1024;
var units = ['B','KB','MB','GB','TB','PB'];
var myBytes = bytes;
var i;
if (mode !== "si" && iunits === true) {
for (i=0; i < units.length; i++) {
if (i) {
var tmpArray = units[i].split('');
tmpArray.splice(1,0,'i');
units[i] = tmpArray.join('');
}
}
}
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];
return (bytes / computedDivisor).toFixed(2) + " " + units[i];
}
}
}
function getBytesFromHumanFilesize (fs) {
var n = fs.replace(/^([0-9]+\.?[0-9]*) B|KB|MB|GB$/, "$1");
var u = fs.replace(/^[0-9]+\.?[0-9]* (B|KB|MB|GB)$/, "$1");
var multiplier = 0;
if (u == "B") multiplier = 0;
else if (u == "KB") multiplier = 1;
else if (u == "MB") multiplier = 2;
else if (u == "GB") multiplier = 3;
else return fs;
return Math.round(parseFloat(n,10) * Math.pow(1024,multiplier));
}