Open In App

JavaScript Convert bytes to human-readable string

Last Updated : 12 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given the size of a file (in Bytes), the task is to convert it into human-readable form using JavaScript. Here are a few methods to discuss. 

Example 1: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in Bytes. 

Javascript




let size = function (bytes) {
    if (bytes === 0) {
        return "0.00 B";
    }
     
    let e = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, e)).toFixed(2) +
        ' ' + ' KMGTP'.charAt(e) + 'B';
}
 
let bytes = 2007777777770;
 
console.log(bytes + " bytes = " + size(bytes));


Output

2007777777770 bytes = 1.83 TB

Example 2: This example converts the file Size(in Bytes) into human-readable form. It shows the values in decimal and for less than 1024 Bytes, it remains in Bytes. But, with a different approach. 

Javascript




function getSize(size) {
    let sizes = [' Bytes', ' KB', ' MB', ' GB',
        ' TB', ' PB', ' EB', ' ZB', ' YB'];
 
    for (let i = 1; i < sizes.length; i++) {
        if (size < Math.pow(1024, i))
            return (Math.round((size / Math.pow(
                1024, i - 1)) * 100) / 100) + sizes[i - 1];
    }
    return size;
}
 
let bytes = 1024;
 
console.log(bytes + " bytes = " + getSize(bytes));


Output

1024 bytes = 1 KB


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads