@@ -111,6 +111,74 @@ def gb(gigabytes): # pylint: disable=C0103
111111 return FormattedItem (int (float (gigabytes )) * 1024 , "%dG" % int (float (gigabytes )))
112112
113113
114+ def convert_sizes (value , unit = 'GB' , round_result = False ):
115+ """Converts a data storage value to an appropriate unit.
116+
117+ :param str value: The value to convert.
118+ :param str unit: The unit of the value ('B', 'KB', 'MB', 'GB', 'TB').
119+ :param bool round_result: rounded result
120+ :return: The converted value and its unit.
121+ """
122+
123+ if not value :
124+ return '0.00 MB'
125+
126+ value = float (value )
127+
128+ if value == 0 :
129+ return "0.00 MB"
130+
131+ units = ['B' , 'KB' , 'MB' , 'GB' , 'TB' ]
132+ if unit not in units :
133+ return "Invalid unit. Must be one of 'B', 'KB', 'MB', 'GB', 'TB'"
134+
135+ unit_index = units .index (unit )
136+
137+ while value > 999 and unit_index < len (units ) - 1 :
138+ value /= 1024
139+ unit_index += 1
140+
141+ while value < 1 and unit_index > 0 :
142+ value *= 1024
143+ unit_index -= 1
144+
145+ if round_result :
146+ value = round (value / 5 ) * 5
147+ return "{:.2f} {}" .format (value , units [unit_index ])
148+
149+
150+ def sum_sizes (size1 , size2 ):
151+ """Sums two data storage values.
152+
153+ :param str size1: The first value and its unit.
154+ :param str size2: The second value and its unit.
155+ :return: The sum of the values and its unit.
156+ """
157+ if size1 == '0.00 MB' :
158+ return size2
159+ if size2 == '0.00 MB' :
160+ return size1
161+
162+ value1 , unit1 = float (size1 .split ()[0 ]), size1 .split ()[1 ]
163+ value2 , unit2 = float (size2 .split ()[0 ]), size2 .split ()[1 ]
164+
165+ units = ['B' , 'KB' , 'MB' , 'GB' , 'TB' ]
166+ if unit1 not in units or unit2 not in units :
167+ return "Invalid unit in one of the sizes. Unit must be one of 'B', 'KB', 'MB', 'GB', 'TB'"
168+
169+ value1 *= (1024 ** units .index (unit1 ))
170+ value2 *= (1024 ** units .index (unit2 ))
171+
172+ total_value = value1 + value2
173+
174+ total_unit = 'B'
175+ while total_value > 999 and total_unit != 'TB' :
176+ total_value /= 1024
177+ total_unit = units [units .index (total_unit ) + 1 ]
178+
179+ return "{:.2f} {}" .format (total_value , total_unit )
180+
181+
114182def blank ():
115183 """Returns a blank FormattedItem."""
116184 return FormattedItem (None , '-' )
0 commit comments