Skip to content

Commit

Permalink
chg: string_value_to_float - use standard byte order conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
RazCrimson committed Feb 13, 2023
1 parent c5be750 commit d66aaf8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
32 changes: 18 additions & 14 deletions glances/globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ def json_dumps_dictlist(data, item):
return None



def string_value_to_float(s):
"""Convert a string with a value and an unit to a float.
Example:
Expand All @@ -342,24 +343,27 @@ def string_value_to_float(s):
float: The value in float
"""
convert_dict = {
None: 1,
'B': 1,
'KB': 1000,
'MB': 1000000,
'GB': 1000000000,
'TB': 1000000000000,
'PB': 1000000000000000,
'KB': 1024,
'MB': 1048576,
'GB': 1073741824,
'TB': 1099511627776,
'PB': 1125899906842624,
'EB': 1152921504606846976,
'ZB': 1180591620717411303424,
'YB': 1208925819614629174706176,
}
unpack_string = [i[0] if i[1] == '' else i[1].upper() for i in re.findall(r'([\d.]+)|([^\d.]+)', s.replace(' ', ''))]
if len(unpack_string) == 2:
value, unit = unpack_string
elif len(unpack_string) == 1:
value = unpack_string[0]
unit = None
else:
cleaned_string = s.strip().upper()
match = re.match(r"^([\d.]+).?([KMGTPEZY]B)?$", cleaned_string)
if not match:
return None

value = match.group(1)
unit = match.group(2) or "B"

try:
value = float(unpack_string[0])
value = float(value)
except ValueError:
return None

return value * convert_dict[unit]
6 changes: 3 additions & 3 deletions unitest.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,9 +294,9 @@ def test_017_programs(self):
def test_018_string_value_to_float(self):
"""Check string_value_to_float function"""
print('INFO: [TEST_018] Check string_value_to_float function')
self.assertEqual(string_value_to_float('32kB'), 32000.0)
self.assertEqual(string_value_to_float('32 KB'), 32000.0)
self.assertEqual(string_value_to_float('15.5MB'), 15500000.0)
self.assertEqual(string_value_to_float('32kB'), 32768.0)
self.assertEqual(string_value_to_float('32 KB'), 32768.0)
self.assertEqual(string_value_to_float('15.5MB'), 16252928.0)
self.assertEqual(string_value_to_float('25.9'), 25.9)
self.assertEqual(string_value_to_float('12'), 12)
self.assertEqual(string_value_to_float('--'), None)
Expand Down

0 comments on commit d66aaf8

Please sign in to comment.