1
0
Fork 0
mirror of https://github.com/borgbackup/borg.git synced 2024-12-26 09:47:58 +00:00

Improve sizeof_fmt()

- Use built-in sign handling
- Format integer correctly when using biggest unit
- Use consistent format inside and outside of loop
This commit is contained in:
Dark Dragon 2020-05-26 18:58:31 +02:00 committed by Thomas Waldmann
parent f2f8692f86
commit 831448684c
2 changed files with 9 additions and 8 deletions

View file

@ -271,16 +271,17 @@ def parse_file_size(s):
def sizeof_fmt(num, suffix='B', units=None, power=None, sep='', precision=2, sign=False):
prefix = '+' if sign and num > 0 else ''
sign = '+' if sign else ''
fmt = '{0:{1}.{2}f}{3}{4}{5}'
prec = 0
for unit in units[:-1]:
if abs(round(num, precision)) < power:
if isinstance(num, int):
return "{}{}{}{}{}".format(prefix, num, sep, unit, suffix)
else:
return "{}{:3.{}f}{}{}{}".format(prefix, num, precision, sep, unit, suffix)
break
num /= float(power)
return "{}{:.{}f}{}{}{}".format(prefix, num, precision, sep, units[-1], suffix)
prec = precision
else:
unit = units[-1]
return fmt.format(num, sign, prec, sep, unit, suffix)
def sizeof_fmt_iec(num, suffix='B', sep='', precision=2, sign=False):

View file

@ -579,7 +579,7 @@ def test_file_size_precision():
def test_file_size_sign():
si_size_map = {
0: '0 B',
0: '+0 B',
1: '+1 B',
1234: '+1.23 kB',
-1: '-1 B',