Skip to content
Related Articles
Open in App
Not now

Related Articles

JavaScript Convert bytes to human-readable string

Improve Article
Save Article
  • Last Updated : 16 Jan, 2023
Improve Article
Save Article

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

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. 

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    up.innerHTML = 'Convert bytes to human readable form';
    var down = document.getElementById('GFG_DOWN');
    size = function(bytes) {
        if (bytes == 0) {
            return "0.00 B";
        }
        var e = Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, e)).toFixed(2) +
        ' ' + ' KMGTP'.charAt(e) + 'B';
    }
      
    function GFG_Fun() {
        var bytes = 2007777777770;
        down.innerHTML = bytes + " bytes = " + size(bytes);
    }
</script>


Output:

JavaScript Convert bytes to human-readable string

JavaScript Convert bytes to human-readable string

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. 

html




<h1 style="color:green;">
    GeeksForGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    up.innerHTML = 'Convert bytes to human readable form';
    var down = document.getElementById('GFG_DOWN');
      
    function getSize(size) {
        var sizes = [' Bytes', ' KB', ' MB', ' GB',
                    ' TB', ' PB', ' EB', ' ZB', ' YB'];
          
        for (var 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;
    }
      
    function GFG_Fun() {
        var bytes = 1024;
        down.innerHTML = bytes + " bytes = " + getSize(bytes);
    }
</script>


Output:

JavaScript Convert bytes to human-readable string

JavaScript Convert bytes to human-readable string


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!