Skip to content

Instantly share code, notes, and snippets.

@hctilg
Last active June 15, 2024 21:10
Show Gist options
  • Save hctilg/1b0c215d545174fb7e36061f950a27f0 to your computer and use it in GitHub Desktop.
Save hctilg/1b0c215d545174fb7e36061f950a27f0 to your computer and use it in GitHub Desktop.
convert bytes to a human-readable string

format-bytes

Convert bytes to a human-readable string.

Description

  • First, we need to get bytes as numbers. If it's not a number, we will convert it to a number.
  • After that, if we didn't get a number or our number was 0, we return "0 B" as output.
  • Then we start finding the value and the unit of bytes that should be returned as a string.

Examples

formatBytes()                                        // 0 B
formatBytes(1024)                                    // 1 KB
formatBytes(1024 * 1024)                             // 1 MB
formatBytes(1024 * 1024 * 9)                         // 9 MB
formatBytes(1024 * 1024 * 1024)                      // 1 GB
formatBytes(1024 * 1024 * 1024 * 9)                  // 9 GB
formatBytes(1024 * 1024 * 1024 * 1024)               // 1 TB
formatBytes(1024 * 1024 * 1024 * 1024 * 9)           // 9 TB
formatBytes(1024 * 1024 * 1024 * 1024 * 1024)        // 1 PB
formatBytes(1024 * 1024 * 1024 * 1024 * 1024 * 9)    // 9 PB

formatBytes(17605591, 0)                             // 17 MB
formatBytes(17605591, 1)                             // 16.8 MB
formatBytes(17605591)                                // 16.79 MB
function formatBytes(bytes, decimals = 2) {
if (Number.isNaN(bytes)) return "Incalculable";
if (!+bytes) return "0 B";
let i = 0;
for (i; bytes >= 1024; i++) bytes /= 1024;
const dm = bytes % 1 === 0 ? 0 : decimals;
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
return `${bytes.toFixed(dm)} ${units[i]}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment