SPB Git

Repository Public

Format.swift 11.2 KB 273 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/Util/Format.swift10// Description      : formats du français du Québec — montants (« 460 100 $ »),11//                    écarts signés (« +6,3 % », « −11,6 % »), étiquettes12//                    compactes (« 460 k$ »), dates, superficies, distances.13// Module           : VraiPrix14// Repository       : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website  : https://www.vrai-prix.com16// Created          : 2026-11-2617// Last Modified    : 2026-11-2618//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293enum Fmt {94    /// espace insécable entre les milliers et avant le symbole (la fine, U+202F, est illisible en SF Pro gras)95    static let thin = "\u{00A0}"96    static let nbsp = "\u{00A0}"97    static let minus = "\u{2212}"98    static let dash = "—"99100    private static let frCA = Locale(identifier: "fr_CA")101102    /// 460100 → « 460 100 »103    static func grouped(_ v: Double) -> String {104        let n = Int64(abs(v).rounded())105        var s = String(n)106        var out = ""107        while s.count > 3 {108            out = thin + s.suffix(3) + out109            s = String(s.dropLast(3))110        }111        return (v < -0.5 ? minus : "") + s + out112    }113114    /// 460100 → « 460 100 $ » ; nil → « — »115    static func money(_ v: Double?) -> String {116        guard let v, v.isFinite else { return dash }117        return grouped(v) + nbsp + "$"118    }119120    /// Montant signé : « +28 900 $ », « −12 000 $ »121    static func signedMoney(_ v: Double?) -> String {122        guard let v, v.isFinite else { return dash }123        return (v >= 0.5 ? "+" : "") + grouped(v) + nbsp + "$"124    }125126    /// Étiquette compacte de carte et de graduation : « 460 k$ », « 1,2 M$ », « 85 k$ »127    static func compact(_ v: Double?) -> String {128        guard let v, v.isFinite else { return dash }129        let a = abs(v)130        let sign = v < 0 ? minus : ""131        if a >= 999_500 {132            let m = a / 1_000_000133            let s = m >= 9.95 ? String(format: "%.0f", m) : String(format: "%.1f", m).replacingOccurrences(of: ".", with: ",")134            return sign + s.replacingOccurrences(of: ",0", with: "") + nbsp + "M$"135        }136        if a >= 1000 { return sign + String(format: "%.0f", a / 1000) + nbsp + "k$" }137        return sign + String(format: "%.0f", a) + nbsp + "$"138    }139140    /// Grand nombre lisible : « 2,01 G$ », « 378,5 G$ », « 3,7 M »141    static func big(_ v: Double?, unit: String = "$") -> String {142        guard let v, v.isFinite else { return dash }143        let a = abs(v)144        func f(_ x: Double, _ d: Int) -> String { String(format: "%.\(d)f", x).replacingOccurrences(of: ".", with: ",") }145        let u = unit.isEmpty ? "" : unit146        if a >= 1e12 { return f(a / 1e12, 2) + nbsp + "billions" + (u.isEmpty ? "" : nbsp + u) }147        if a >= 1e9 { return f(a / 1e9, 1) + nbsp + "G" + u }148        if a >= 1e6 { return f(a / 1e6, 1) + nbsp + "M" + u }149        return grouped(a) + (u.isEmpty ? "" : nbsp + u)150    }151152    /// Nombre entier groupé : « 3 747 008 »153    static func int(_ v: Int?) -> String {154        guard let v else { return dash }155        return grouped(Double(v))156    }157158    /// Écart signé en pourcentage, à partir d'un pourcentage (6.3 → « +6,3 % ») ; vrai signe moins.159    static func pct(_ p: Double?, digits: Int = 1) -> String {160        guard let p, p.isFinite else { return dash }161        let r = (abs(p) * pow(10, Double(digits))).rounded() / pow(10, Double(digits))162        let s = String(format: "%.\(digits)f", r).replacingOccurrences(of: ".", with: ",")163        let sign = r == 0 ? "" : (p > 0 ? "+" : minus)164        return sign + s + nbsp + "%"165    }166167    /// Pourcentage sans signe à partir d'une fraction (0.2159 → « 21,6 % »).168    static func share(_ f: Double?, digits: Int = 1) -> String {169        guard let f, f.isFinite else { return dash }170        return String(format: "%.\(digits)f", f * 100).replacingOccurrences(of: ".", with: ",") + nbsp + "%"171    }172173    static func decimal(_ v: Double?, digits: Int = 1) -> String {174        guard let v, v.isFinite else { return dash }175        return String(format: "%.\(digits)f", v).replacingOccurrences(of: ".", with: ",")176    }177178    // MARK: Dates179180    private static let isoDay: DateFormatter = {181        let f = DateFormatter()182        f.locale = Locale(identifier: "en_US_POSIX")183        f.timeZone = TimeZone(identifier: "America/Toronto")184        f.dateFormat = "yyyy-MM-dd"185        return f186    }()187188    private static func formatter(_ format: String) -> DateFormatter {189        let f = DateFormatter()190        f.locale = frCA191        f.timeZone = TimeZone(identifier: "America/Toronto")192        f.dateFormat = format193        return f194    }195196    private static let longDay = formatter("d MMMM yyyy")197    private static let shortDay = formatter("d MMM yyyy")198    private static let monthYear = formatter("MMMM yyyy")199    private static let shortMonthYear = formatter("MMM yyyy")200201    static func date(iso: String?) -> Date? {202        guard let iso, iso.count >= 10 else { return nil }203        return isoDay.date(from: String(iso.prefix(10)))204    }205206    /// « 2024-03-14 » → « 14 mars 2024 »207    static func day(_ iso: String?, short: Bool = false) -> String {208        guard let d = date(iso: iso) else { return iso ?? dash }209        return (short ? shortDay : longDay).string(from: d)210    }211212    /// « 2026-07 » → date du premier du mois213    static func monthDate(_ ym: String?) -> Date? {214        guard let ym, ym.count >= 7 else { return nil }215        return isoDay.date(from: String(ym.prefix(7)) + "-01")216    }217218    /// « 2026-07 » → « juillet 2026 »219    static func month(_ ym: String?, short: Bool = false) -> String {220        guard let d = monthDate(ym) else { return ym ?? dash }221        return (short ? shortMonthYear : monthYear).string(from: d)222    }223224    static func day(_ date: Date) -> String { longDay.string(from: date) }225226    static func day(epoch: Double?) -> String {227        guard let epoch, epoch > 0 else { return dash }228        return longDay.string(from: Date(timeIntervalSince1970: epoch))229    }230231    // MARK: Mesures232233    /// Superficie en m² et en pi² : « 395,5 m² (4 257 pi²) »234    static func area(m2: Double?, both: Bool = true) -> String {235        guard let m2, m2 > 0 else { return dash }236        let a = (m2 >= 1000 ? grouped(m2) : decimal(m2, digits: m2 < 100 ? 1 : 0)) + nbsp + "m²"237        return both ? a + " (" + grouped(m2 * 10.7639) + nbsp + "pi²)" : a238    }239240    static func area(sqft: Double?) -> String {241        guard let sqft, sqft > 0 else { return dash }242        return grouped(sqft) + nbsp + "pi²"243    }244245    static func distance(m: Double?) -> String {246        guard let m, m.isFinite else { return dash }247        if m < 950 { return String(format: "%.0f", max(10, (m / 10).rounded() * 10)) + nbsp + "m" }248        return decimal(m / 1000, digits: m < 10_000 ? 1 : 0) + nbsp + "km"249    }250251    /// « 5681 Rue Campanules » reste tel quel ; les majuscules criardes du rôle (« Avenue PRATT ») sont adoucies.252    static func address(_ s: String?) -> String {253        guard let s = s?.trimmingCharacters(in: .whitespaces), !s.isEmpty else { return "Adresse non précisée" }254        return s.split(separator: " ").map { w -> String in255            let word = String(w)256            let letters = word.filter(\.isLetter)257            if letters.count > 2, letters == letters.uppercased() { return word.prefix(1) + word.dropFirst().lowercased() }258            return word259        }.joined(separator: " ")260    }261262    /// Majuscule initiale (« copropriété » → « Copropriété »).263    static func capitalized(_ s: String) -> String { s.prefix(1).uppercased() + s.dropFirst() }264265    /// Âge d'une vente en mois → « il y a 7 mois », « ce mois-ci », « il y a 2 ans »266    static func ago(months: Double?) -> String {267        guard let m = months, m.isFinite else { return dash }268        if m < 1 { return "ce mois-ci" }269        if m < 24 { return "il y a \(Int(m.rounded())) mois" }270        return "il y a \(Int((m / 12).rounded())) ans"271    }272}273
Files main
Menu

Theme