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)