From 357857adc074ffe005bc6a5a087c17cb3127250b Mon Sep 17 00:00:00 2001
From: Alan De Smet <alan.desmet@ssec.wisc.edu>
Date: Fri, 6 Aug 2021 14:21:13 -0500
Subject: [PATCH] Proper rounding for csppfetch.human_bytes;+doctest
---
csppfetch/__init__.py | 34 +++++++++++++++++++++++++++++-----
csppfetch/test.py | 1 +
2 files changed, 30 insertions(+), 5 deletions(-)
diff --git a/csppfetch/__init__.py b/csppfetch/__init__.py
index 94e6b87..fa1e100 100644
--- a/csppfetch/__init__.py
+++ b/csppfetch/__init__.py
@@ -96,21 +96,45 @@ class FileSet:
def human_bytes(total_bytes):
+ """ return nicely formatted string for a count of bytes
+
+ The result is rounded to the displayed precision,
+ so (1024**2)-512 is "1.00 MiB" but (1024**2)-513 is "1023 KiB"
+
+ >>> human_bytes(0)
+ '0 B'
+ >>> human_bytes(3836163)
+ '3.66 MiB'
+ >>> human_bytes((1024**2)-512)
+ '1.00 MiB'
+ >>> human_bytes((1024**2)-513)
+ '1023 KiB'
+ >>> human_bytes(7763153400)
+ '7.23 GiB'
+ """
step_size = 1024
+ # Yes, it's "Ki", not "ki".
steps = "Ki Mi Gi Ti Pi Ei".split()
# If you prefer the non-binary SI prefixes
# step_size = 1000
- # steps = [""]+list("kMGTPE")
+ # steps = "kMGTPE"
if total_bytes < step_size:
return f"{total_bytes} B"
value = total_bytes
step = -1
- while value >= step_size:
+ while round(value,0) >= step_size:
step += 1
value /= step_size
- value_str = f"{value:f}"[:4]
- if value_str[-1] == ".":
- value_str = value_str[:-1]
+
+ if round(value, 2) < 10:
+ value = round(value, 2)
+ value_str = f"{value:.2f}"
+ elif round(value, 1) < 100:
+ value = round(value, 1)
+ value_str = f"{value:.1f}"
+ else:
+ value = round(value, 0)
+ value_str = f"{value:.0f}"
return f"{value_str} {steps[step]}B"
diff --git a/csppfetch/test.py b/csppfetch/test.py
index 7877862..fc5de6e 100755
--- a/csppfetch/test.py
+++ b/csppfetch/test.py
@@ -708,6 +708,7 @@ def load_tests(loader, tests, ignore):
'Downloader': csppfetch.Downloader,
'FileSet': csppfetch.FileSet,
'ShadowEnvironment': ShadowEnvironment,
+ 'human_bytes': csppfetch.human_bytes,
# Functions
'download_all': csppfetch.download_all,
--
GitLab