Coretex
number.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from decimal import Decimal, ROUND_HALF_UP
19 
20 
21 def mathematicalRound(value: float, decimalPlaces: int) -> float:
22  """
23  Performes mathematical (ROUND_HALF_UP) rounding
24  Ex. >= 1.5 will be rounded to 2, < 1.5 will be rounded to 1
25 
26  Parameters
27  ----------
28  value : float
29  value to be rounded
30  decimalPlaces : int
31  amount of decimal places to which the value will be rounded
32 
33  Returns
34  -------
35  float -> the rounded value
36  """
37 
38  decimal = Decimal(str(value))
39  places = Decimal(10) ** -decimalPlaces
40 
41  return float(decimal.quantize(places, rounding = ROUND_HALF_UP))
42 
43 
44 def formatBytes(value: int, precision: int = 2) -> str:
45  """
46  Formats a size in bytes into a human-readable format
47  Ex. value 1444 will be formatted as 1.44 KB
48 
49  Parameters
50  ----------
51  value : int
52  size in bytes
53  precision : int
54  number of decimal places (default is 2)
55 
56  Returns
57  -------
58  str -> formatted string with size and appropriate unit
59  """
60 
61  suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
62  index = 0
63  unitBase = 1000
64  adjustedValue = float(value)
65 
66  while adjustedValue >= unitBase and index < len(suffixes) - 1:
67  index += 1
68  adjustedValue /= unitBase
69 
70  return f"{adjustedValue:.{precision}f} {suffixes[index]}"