Add function to humanize numbers

This commit is contained in:
Odd Stråbø 2021-11-08 22:41:17 +01:00
parent 4266893111
commit 6e28343a08

View file

@ -159,6 +159,36 @@ CMD_ = b"\xff\x78\x00\x00\x00\x01"
# ?: load_enabled # ?: load_enabled
# Only factor of 1000
SI_PREFIXES_LARGE = "kMGTPEZY"
SI_PREFIXES_SMALL = "mµnpfazy"
def humanize_number(data, unit: str = ""):
counter = 0
while data >= 1000:
data /= 1000
counter += 1
if counter >= len(SI_PREFIXES_LARGE):
break
while data < 1:
data *= 1000
counter -= 1
if abs(counter) >= len(SI_PREFIXES_SMALL):
break
if not counter:
prefix = ""
elif counter > 0:
prefix = SI_PREFIXES_LARGE[counter - 1]
elif counter < 0:
prefix = SI_PREFIXES_SMALL[abs(counter) - 1]
return f"{data:.3g} {prefix}{unit}"
class DataItem: class DataItem:
name: str name: str
st_format: str st_format: str
@ -187,7 +217,6 @@ class DataItem:
def transform(self, data): def transform(self, data):
if self.transformation is None: if self.transformation is None:
return data return data
return self.transformation(data) return self.transformation(data)