Add function to humanize numbers
This commit is contained in:
parent
4266893111
commit
6e28343a08
1 changed files with 30 additions and 1 deletions
31
solar_ble.py
31
solar_ble.py
|
@ -159,6 +159,36 @@ CMD_ = b"\xff\x78\x00\x00\x00\x01"
|
|||
# ?: 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:
|
||||
name: str
|
||||
st_format: str
|
||||
|
@ -187,7 +217,6 @@ class DataItem:
|
|||
def transform(self, data):
|
||||
if self.transformation is None:
|
||||
return data
|
||||
|
||||
return self.transformation(data)
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue