Skip to content

Function.formatBytes

github-actions[bot] edited this page Nov 18, 2026 · 13 revisions

umt / formatBytes

Function: formatBytes()

formatBytes(bytes, decimals?): string

Defined in: Number/formatBytes.ts:24

Formats a byte count as a human-readable string using base 1024. The unit is the largest of B, KB, MB, GB, TB and PB that does not exceed the absolute value (values of a PB or more stay in PB). The value is rounded to decimals places with Math.round semantics and printed without trailing zeros.

Parameters

bytes

number

The number of bytes (may be negative or fractional)

decimals?

number = 2

The number of decimal places (default 2)

Returns

string

The formatted size, such as "1.5 KB"

Example

formatBytes(0);              // "0 B"
formatBytes(1024);           // "1 KB"
formatBytes(1536);           // "1.5 KB"
formatBytes(1_234_567);      // "1.18 MB"
formatBytes(1_234_567, 0);   // "1 MB"
formatBytes(-2048);          // "-2 KB"

API

Classes

Interfaces

Type Aliases

Variables

Functions

Clone this wiki locally