💾 Formats a number of bytes into a human-readable string.

Syntax

TypeScript
import { formatBytes } from '@opentf/std';

formatBytes(bytes: number, options?: { decimals?: number; binary?: boolean }): string

Parameters

NameTypeDescription
bytesnumberThe number of bytes.
optionsobjectThe options object.
options.decimalsnumberThe number of decimal places (default 2).
options.binarybooleanIf true, use 1024 as base (KiB); otherwise 1000 (KB) (default true).

options.decimals must be an integer between 0 and 100.

Values smaller than 1 byte stay in the B unit instead of overflowing to an invalid smaller unit.

Returns

The formatted string with appropriate unit (B, KiB/MiB/GiB for binary, KB/MB/GB for decimal).

Examples

TypeScript
formatBytes(0) //=> '0 B'

formatBytes(1023) //=> '1023 B'

formatBytes(1024) //=> '1 KiB'

formatBytes(1536) //=> '1.5 KiB'

formatBytes(0.5) //=> '0.5 B'

formatBytes(1234567) //=> '1.18 MiB'

formatBytes(1234567, { decimals: 0 }) //=> '1 MiB'

formatBytes(-1024) //=> '-1 KiB'

formatBytes(1000, { binary: false }) //=> '1 KB' (using 1000 as base)
Last updated on
Edit this page