parse_size¶
- pyhelpers.ops.parse_size(size, binary=True, precision=1)[source]¶
Parse size into human-readable format or vice versa.
- Parameters:
size (str | int | float) – Size to be parsed, either in human-readable format (e.g.
'10 MB'
) or as an integer.binary (bool) – Whether to use binary (factorised by 1024) or decimal (factorised by 10 ** 3) representation; defaults to
True
for binary representation.precision (int) – Number of decimal places when converting
size
to human-readable format; defaults to1
.
- Returns:
Parsed size, either as an integer (for machine-readable) or a formatted string (for human-readable).
- Return type:
int | str
Examples:
>>> from pyhelpers.ops import parse_size >>> parse_size(size='123.45 MB') 129446707 >>> parse_size(size='123.45 MB', binary=False) 123450000 >>> parse_size(size='123.45 MiB', binary=True) 129446707 >>> # If a metric unit (e.g. 'MiB') is specified in the input, >>> # the function returns a result accordingly, regardless of `binary` >>> parse_size(size='123.45 MiB', binary=False) 129446707 >>> parse_size(size=129446707, precision=2) '123.45 MiB' >>> parse_size(size=129446707, binary=False, precision=2) '129.45 MB'