Skip to content

Commit

Permalink
Helper function localize_decimal() was simplified for better performance
Browse files Browse the repository at this point in the history
  • Loading branch information
titov-vv committed Feb 11, 2024
1 parent 7161b3e commit fccae42
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 26 deletions.
21 changes: 20 additions & 1 deletion jal/constants.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from PySide6.QtCore import Property, QObject
from PySide6.QtCore import Property, QObject, QLocale
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QComboBox


#-----------------------------------------------------------------------------------------------------------------------
# This class contains a list of predefined constants used by JAL
class Setup:
DB_PATH = "jal.sqlite"
DB_CONNECTION = "JAL.DB"
Expand All @@ -29,6 +31,23 @@ class Setup:
MAX_TIMESTAMP = 9999999999


#-----------------------------------------------------------------------------------------------------------------------
# This class is initialized with global values that is used by JAL
class JalGlobals:
number_decimal_point = None
number_group_separator = None

def __init__(self):
if self.number_decimal_point is None:
JalGlobals.init_values()

@classmethod
def init_values(cls):
cls.number_decimal_point = QLocale().decimalPoint()
cls.number_group_separator = QLocale().groupSeparator()


#-----------------------------------------------------------------------------------------------------------------------
class BookAccount: # PREDEFINED BOOK ACCOUNTS
Costs = 1
Incomes = 2
Expand Down
45 changes: 21 additions & 24 deletions jal/db/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from datetime import datetime, timezone, timedelta
from decimal import Decimal, InvalidOperation
from PySide6.QtCore import QLocale
from jal.constants import Setup
from jal.constants import Setup, JalGlobals


# -------------------------------------------------------------------------------------------------------------------
Expand All @@ -27,31 +27,28 @@ def localize_decimal(value: Decimal, precision: int = None, percent: bool = Fals
return Setup.NULL_VALUE
if percent:
value *= Decimal('100')
value = remove_exponent(value)
has_sign, digits, exponent = remove_exponent(value).as_tuple()
value = -value if has_sign else value # Remove sign. It will be added back at the end.
try:
precision = int(precision)
except (ValueError, TypeError):
precision = -exponent
rounded = round(value, precision)
digits = [digit for digit in str(rounded)] # Represent string as list for easier insertions/replacements
if 'E' in digits:
digits[1] = QLocale().decimalPoint()
f_str = '{:'
if sign:
f_str += '+'
f_str += ','
if precision:
f_str += f".{precision}"
if abs(value) > 1:
f_str += "f}"
else:
if precision > 0:
digits[-precision - 1] = QLocale().decimalPoint() # Replace decimal point with locale-specific value
integer_part_size = len(digits) - precision - 1
f_str += "G}"
formatted_number = f_str.format(value)
pos = formatted_number.find('.')
if pos==0:
formatted_number = '0' + formatted_number
pos += 1
if pos > 0:
if precision is not None:
formatted_number = formatted_number[:pos+precision+1]
else:
integer_part_size = len(digits) # No decimal point is present in number
if QLocale().groupSeparator():
for i in range(3, integer_part_size, 3): # Insert locale-specific thousand separator at each 3rd digit
digits.insert(integer_part_size - i, QLocale().groupSeparator())
if has_sign:
digits.insert(0, QLocale().negativeSign())
elif sign:
digits.insert(0, QLocale().positiveSign())
formatted_number = ''.join(digits)
formatted_number = formatted_number.rstrip('0')
formatted_number = formatted_number[:-1] if formatted_number[-1]=='.' else formatted_number
formatted_number = formatted_number.replace(',', JalGlobals().number_group_separator).replace('.', JalGlobals().number_decimal_point)
return formatted_number


Expand Down
3 changes: 2 additions & 1 deletion jal/widgets/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from jal.widgets.icons import JalIcon
from jal.widgets.reference_dialogs import AccountListDialog, AssetListDialog, TagsListDialog,\
CategoryListDialog, QuotesListDialog, PeerListDialog, BaseCurrencyDialog
from jal.constants import Setup
from jal.constants import Setup, JalGlobals
from jal.db.backup_restore import JalBackup
from jal.db.helpers import get_app_path, get_dbfilename
from jal.db.account import JalAccount
Expand All @@ -35,6 +35,7 @@
class MainWindow(QMainWindow):
def __init__(self, language):
super().__init__()
self.globals = JalGlobals() # Initialize and keep global values
self.icons = JalIcon() # This variable is used to initialize JalIcons class and keep its cache in memory.
# It is not used directly but icons are accessed via @classmethod of JalIcons class
# Should be called before ui-initialization
Expand Down

0 comments on commit fccae42

Please sign in to comment.