__all__ = ["decimal"]
from typing import Iterable, List, Optional, Tuple
def _to_str(
size: int,
suffixes: Iterable[str],
base: int,
*,
precision: Optional[int] = 1,
separator: Optional[str] = " ",
) -> str:
if size == 1:
return "1 byte"
elif size < base:
return "{:,} bytes".format(size)
for i, suffix in enumerate(suffixes, 2): unit = base**i
if size < unit:
break
return "{:,.{precision}f}{separator}{}".format(
(base * size / unit),
suffix,
precision=precision,
separator=separator,
)
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
for i, suffix in enumerate(suffixes):
unit = base**i
if size < unit * base:
break
return unit, suffix
def decimal(
size: int,
*,
precision: Optional[int] = 1,
separator: Optional[str] = " ",
) -> str:
return _to_str(
size,
("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
1000,
precision=precision,
separator=separator,
)