formatFileSize(bytes)

The formatFileSize() function converts a file size in bytes to a human-readable string representation with appropriate units.

// Format 1500 bytes to a readable size
readableSize = formatFileSize(1500)  // "1.46 KB"

Syntax

formatFileSize(sizeInBytes)

Parameters

  • sizeInBytes: Number - The file size in bytes to format

Return Value

Returns a string representing the file size with an appropriate unit (B, KB, MB, GB, etc.).

Description

The formatFileSize() function takes a numeric value representing a file size in bytes and converts it to a human-readable string with the most appropriate unit. It automatically selects between bytes, kilobytes, megabytes, gigabytes, etc., based on the size of the input value.

This function is particularly useful when:

  • Displaying file sizes in user interfaces

  • Reporting download or upload sizes

  • Showing disk usage information

  • Working with file system operations

Examples

Basic Usage

Practical Example with File Listing

Using with File Upload UI

Notes

  • The function typically rounds to 2 decimal places for readability.

  • For very large files, the function will use the appropriate unit (TB, PB, etc.)

  • For very small files, bytes (B) will be used without decimal places.

  • The exact formatting may vary slightly depending on the implementation.

Last updated

Was this helpful?