Correct way to convert size in bytes to KB, MB, GB in JavaScript
This solution includes a decimal point and a tenths-place digit if presenting less than ten of KB or greater units
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
function niceBytes(x){
let l = 0, n = parseInt(x, 10) || 0;
while(n >= 1024 && ++l){
n = n/1024;
}
return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}
Results:
niceBytes(435) // 435 bytes
niceBytes(3398) // 3.3 KB
niceBytes(490398) // 479 KB
niceBytes(6544528) // 6.2 MB
niceBytes(23483023) // 22 MB
niceBytes(3984578493) // 3.7 GB
niceBytes(30498505889) // 28 GB
niceBytes(9485039485039445) // 8.4 PB
function formatBytes(bytes) {
var marker = 1024; // Change to 1000 if required
var decimal = 3; // Change as required
var kiloBytes = marker; // One Kilobyte is 1024 bytes
var megaBytes = marker * marker; // One MB is 1024 KB
var gigaBytes = marker * marker * marker; // One GB is 1024 MB
var teraBytes = marker * marker * marker * marker; // One TB is 1024 GB
// return bytes if less than a KB
if(bytes < kiloBytes) return bytes + " Bytes";
// return KB if less than a MB
else if(bytes < megaBytes) return(bytes / kiloBytes).toFixed(decimal) + " KB";
// return MB if less than a GB
else if(bytes < gigaBytes) return(bytes / megaBytes).toFixed(decimal) + " MB";
// return GB if less than a TB
else return(bytes / gigaBytes).toFixed(decimal) + " GB";
}
From this: (source)
Unminified and ES6'ed: (by the community)
function formatBytes(bytes, decimals = 2) {
if (!+bytes) 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]}`
}
// Demo code
document.body.innerHTML += `<input type="text" oninput="document.querySelector('p').innerHTML=formatBytes(this.value)" value="1000"><p>1000 Bytes</p>`
Minified version (by StackOverflow's community, minified by JSCompress)
function formatBytes(a,b=2){if(!+a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return`${parseFloat((a/Math.pow(1024,d)).toFixed(c))} ${["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}`}
Usage:
// formatBytes(bytes, decimals)
formatBytes(1024) // 1 KB
formatBytes('1024') // 1 KB
formatBytes(1234) // 1.21 KB
formatBytes(1234, 3) // 1.205 KB
formatBytes(0) // 0 Bytes
formatBytes('0') // 0 Bytes
PS : Change k = 1000
or sizes = ["..."]
as you want (bits or bytes)