import Foundation enum CurrencyFormatter { static func currentCurrencyCode() -> String { let context = CoreDataStack.shared.viewContext return AppSettings.getOrCreate(in: context).currency } static func locale(for currencyCode: String?) -> Locale { guard let currencyCode, !currencyCode.isEmpty else { return Locale.current } if let match = Locale.availableIdentifiers.first(where: { Locale(identifier: $0).currency?.identifier == currencyCode }) { return Locale(identifier: match) } return Locale.current } static func format(_ decimal: Decimal, style: NumberFormatter.Style = .currency, maximumFractionDigits: Int = 2) -> String { let formatter = NumberFormatter() formatter.numberStyle = style formatter.currencyCode = currentCurrencyCode() formatter.maximumFractionDigits = maximumFractionDigits return formatter.string(from: decimal as NSDecimalNumber) ?? "\(decimal)" } static func format( _ decimal: Decimal, currencyCode: String?, style: NumberFormatter.Style = .currency, maximumFractionDigits: Int = 2, preferredLocale: Locale? = nil ) -> String { let formatter = NumberFormatter() formatter.numberStyle = style formatter.currencyCode = currencyCode ?? currentCurrencyCode() formatter.maximumFractionDigits = maximumFractionDigits formatter.locale = preferredLocale ?? locale(for: currencyCode) return formatter.string(from: decimal as NSDecimalNumber) ?? "\(decimal)" } static func symbol(for code: String) -> String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencyCode = code return formatter.currencySymbol ?? code } }