"""Formatting utilities for display and presentation.""" from abacus_common_logic.constants.math import Bytes _SORTED_BYTE_UNITS = tuple(sorted(Bytes, key=lambda x: x.value)) def format_bytes(file_bytes: int, show_sign: bool = False) -> str: """Format byte size into human-readable string with appropriate unit. Args: file_bytes: Size in bytes. show_sign: If True, prepends '+' to positive values. Negative values always show '-'. Returns: str: Formatted size string (e.g., "1.50 MB", "150.00 KB", "5.00 B"). """ # Find appropriate unit abs_bytes = abs(file_bytes) unit = Bytes.B for u in _SORTED_BYTE_UNITS: if abs_bytes < u.value: break unit = u # Convert to unit value = file_bytes / unit.value # Return formatted string pos_sign = '+' if show_sign and file_bytes > 0 else '' return f'{pos_sign}{value:.2f} {unit.name}'