"""Definition of readable_unit function.""" def readable_unit(value: float, unit: str) -> str: """Return the given number formatted as a readable string with the specified unit. Args: value (float): The numeric value to format. unit (str): The unit to append to the formatted value. Returns: str: A string representation of the value with the unit, formatted to two decimal places. """ if not isinstance(value, (int, float)): raise ValueError("Value must be a number.") if value < 0: raise ValueError("Value cannot be negative.") if not isinstance(unit, str): raise ValueError("Unit must be a string.") if unit.strip() == "": raise ValueError("Unit cannot be an empty string.") # Stop early if value is less than 1 if value < 1: return f"{value:.2f} {unit}" # List of (suffix, factor), ordered from largest to smallest factors = [ ("Y", 2**80), ("Z", 2**70), ("E", 2**60), ("P", 2**50), ("T", 2**40), ("G", 2**30), ("M", 2**20), ("K", 2**10), ("", 1), ] # Find the largest factor that fits the value for suffix, factor in factors: if factor <= value: value /= factor break # Build response return f"{value:.2f} {suffix}{unit}"