From 15b6abfdf3ee581698ddee2031859afc577c26ea Mon Sep 17 00:00:00 2001 From: Christian Herdtweck Date: Fri, 5 Feb 2016 11:27:13 +0100 Subject: [PATCH] also deal with differences in size_str --- src/file_helpers.py | 27 +++++++++++++++++++++------ 1 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/file_helpers.py b/src/file_helpers.py index b9e932b..e98937c 100644 --- a/src/file_helpers.py +++ b/src/file_helpers.py @@ -404,24 +404,39 @@ def find_mount_point(path): return path -def size_str(byte_number): - """ round byte_number to something easily human-readable like '1.5G' """ +def size_str(byte_number, is_diff=False): + """ round byte_number to something easily human-readable like '1.5G' + :param bool is_diff: set to True to include a '+' or '-' in output; + default: False + """ + + # constants units = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' factor = 1024 thresh_add_comma = 10. # below this, return 1.2G, above this return 12G + # prepare + if byte_number < 0: + sign_str = '-' + elif is_diff: + sign_str = '+' + else: + sign_str = '' curr_fac = 1 - curr_num = float(byte_number) + curr_num = abs(float(byte_number)) + + # loop for unit in units: if curr_num > factor: curr_num /= factor continue elif curr_num < thresh_add_comma and unit != 'B': # e.g. 1.2G - return '{0:.1f}{1}'.format(curr_num, unit) + return '{2}{0:.1f}{1}'.format(curr_num, unit, sign_str) else: # e.g. 12G or 1B - return '{0:d}{1}'.format(int(round(curr_num)), unit) + return '{2}{0:d}{1}'.format(int(round(curr_num)), unit, sign_str) # have an impossible amount of data. (>1024**4 GB) # undo last "/factor" and show thousand-separator - return '{0:,d}{1}'.format(int(round(curr_num*factor)), units[-1]) + return '{2}{0:,d}{1}'.format(int(round(curr_num*factor)), units[-1], + sign_str) -- 1.7.1