Convert Bytes to KB, MB, GB Using JavaScript and PHP


When working with file sizes, it's essential to display them in a human-readable format instead of raw bytes. A small file might be a few KB, while larger files could be in MB, GB, or even TB.

This page demonstrates how to convert raw byte values into human-readable formats using both JavaScript and PHP implementations of a formatBytes function. The function handles various input types and converts them to appropriate units from Bytes (B) to Yottabytes (YB).

Demo: Online Byte Converter

Convert Bytes to KB, MB, GB in JavaScript

JavaScript provides a simple way to format file sizes dynamically. You can use a function to convert bytes into KB, MB, GB, and beyond based on the file size. Below is a JavaScript function to handle this conversion.

JavaScript
const formatBytes = (input, precision = 2) => {
    const bytes = Number(input);

    if (!Number.isFinite(bytes) || bytes < 0) return '0 B';

    const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    if (bytes < 1024) return `${bytes} B`;

    const unitIndex = Math.floor(Math.log10(bytes) / Math.log10(1024));
    const value = bytes / Math.pow(1024, unitIndex);

    return `${value.toFixed(precision).replace(/\.?0+$/, '')} ${units[unitIndex]}`;
};

Usage:

JavaScript
// Example Usage
console.log(formatBytes(1048576));        // Default precision: "1 MB"
console.log(formatBytes(1048576, 3));     // "1.000 MB"
console.log(formatBytes(123456789, 1));   // "117.7 MB"
console.log(formatBytes(1024, 0));        // "1 KB"

Features

  • Handles invalid inputs (null, undefined, negative numbers)
  • Removes non-numeric characters from input
  • Supports units from Bytes to Yottabytes
  • Removes trailing zeros for cleaner output
  • Automatically scales to appropriate unit

Convert Bytes to KB, MB, GB in PHP

If you are handling file uploads or displaying file sizes on a server-side application, PHP can format file sizes efficiently. Below is a PHP function that converts bytes into a readable format.

PHP
<?php
function formatBytes($input, $precision = 2) {
    $bytes = floatval($input);

    if (!is_finite($bytes) || $bytes < 0) {
        return '0 B';
    }

    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    if ($bytes < 1024) {
        return $bytes . ' B';
    }

    $unitIndex = floor(log($bytes, 1024));
    $value = $bytes / pow(1024, $unitIndex);

    return rtrim(rtrim(number_format($value, $precision, '.', ''), '0'), '.') . ' ' . $units[$unitIndex];
}

Usage:

PHP
<?php
// Example Usage
echo formatBytes(1048576) . "\n";       // Default precision: "1 MB"
echo formatBytes(1048576, 3) . "\n";    // "1.000 MB"
echo formatBytes(123456789, 1) . "\n";  // "117.7 MB"
echo formatBytes(1024, 0) . "\n";       // "1 KB"

Convert and Display File Size in a Human-Readable Format

How to display file sizes in a user-friendly format using PHP and JavaScript. This demo showcases how to convert raw bytes into KB, MB, GB, and beyond, making file size information easier to understand.

PHP example:

PHP
<?php
$file = 'myfile.zip'; // Replace with your actual file path
if (file_exists($file)) {
    $file_size = filesize($file); // Get file size in bytes
    echo '<div title="' . $file_size . ' bytes">' . formatBytes($file_size) . '</div>';
} else {
    echo "File not found!";
}
// output
// <div title="1073741824 bytes">1.00 GB</div>

JavaScript example:

HTML and JavaScript
<input type="file" id="fileInput">
<div id="output"></div>

<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const fileSize = file.size; // Get file size in bytes
        const formattedSize = formatBytes(fileSize);

        document.getElementById('output').innerHTML =
            `<div title="${fileSize} bytes">${formattedSize}</div>`;
    }
});
</script>