SPB Git

Repository Public

Formatting.swift 6.3 KB 152 lines swift

1import Foundation2import SheetCore34/// How a result value is shown in a panel and which number format it gets when written into a sheet.5public enum CellFormat: Sendable, Hashable {6    /// Chosen from the magnitude of each value.7    case auto8    case integer9    case fixed(Int)10    /// A fraction shown as a percentage with the given decimals (0.0525 → 5.25 %).11    case percent(Int)12    /// Two decimals with thousands separators.13    case money14    /// Four decimals; values below 0.0001 are shown as "< 0.0001".15    case pValue16    case scientific17    /// Spreadsheet serial date.18    case date19    /// An explicit number-format code.20    case code(String)2122    /// Number-format code written into the sheet for `value`.23    public func code(for value: Double) -> String {24        switch self {25        case .auto: return CellFormat.autoCode(value)26        case .integer: return abs(value) >= 10_000 ? "#,##0" : "0"27        case .fixed(let d): return (abs(value) >= 1000 ? "#,##0" : "0") + (d <= 0 ? "" : "." + String(repeating: "0", count: d))28        case .percent(let d): return (d <= 0 ? "0" : "0." + String(repeating: "0", count: d)) + "%"29        case .money: return "#,##0.00"30        case .pValue: return "0.0000"31        case .scientific: return "0.000E+00"32        case .date: return "yyyy-mm-dd"33        case .code(let c): return c34        }35    }3637    static func autoCode(_ x: Double) -> String {38        let a = abs(x)39        if a == 0 { return "0" }40        if x == x.rounded(), a < 1e15 { return a >= 10_000 ? "#,##0" : "0" }41        if a >= 1e9 { return "0.000E+00" }42        if a >= 1000 { return "#,##0.00" }43        if a >= 0.001 { return "0.0000" }44        return "0.000E+00"45    }46}4748/// Locale-aware text for numbers shown in the panels.49public enum Fmt {50    private static func formatter(_ locale: Locale, min: Int, max: Int, grouping: Bool) -> NumberFormatter {51        let f = NumberFormatter()52        f.locale = locale53        f.numberStyle = .decimal54        f.minimumFractionDigits = min55        f.maximumFractionDigits = max56        f.usesGroupingSeparator = grouping57        return f58    }5960    public static func fixed(_ x: Double, _ decimals: Int, grouping: Bool = true, locale: Locale = .current) -> String {61        guard x.isFinite else { return x.isNaN ? "—" : (x > 0 ? "∞" : "−∞") }62        let k = pow(10, Double(decimals))63        let v = (x * k).rounded() == 0 ? 0 : x      // no "-0" or "-0.0000"64        return formatter(locale, min: decimals, max: decimals, grouping: grouping).string(from: NSNumber(value: v)) ?? String(v)65    }6667    public static func integer(_ x: Double, locale: Locale = .current) -> String { fixed(x.rounded(), 0, locale: locale) }68    public static func integer(_ x: Int, locale: Locale = .current) -> String { fixed(Double(x), 0, locale: locale) }6970    /// General-purpose figure: 4 decimals below 1000, 2 above, scientific for the very small or very large.71    public static func number(_ x: Double, locale: Locale = .current) -> String {72        guard x.isFinite else { return fixed(x, 0) }73        let a = abs(x)74        if a == 0 { return "0" }75        if x == x.rounded(), a < 1e15 { return fixed(x, 0, locale: locale) }76        if a >= 1e9 || a < 0.0001 { return scientific(x, locale: locale) }77        if a >= 1000 { return fixed(x, 2, locale: locale) }78        return fixed(x, 4, locale: locale)79    }8081    public static func scientific(_ x: Double, locale: Locale = .current) -> String {82        guard x.isFinite else { return fixed(x, 0) }83        let f = NumberFormatter()84        f.locale = locale85        f.numberStyle = .scientific86        f.minimumFractionDigits = 387        f.maximumFractionDigits = 388        f.exponentSymbol = "E"89        return f.string(from: NSNumber(value: x)) ?? String(x)90    }9192    /// "5.25 %" (the argument is a fraction).93    public static func percent(_ x: Double, _ decimals: Int = 2, locale: Locale = .current) -> String {94        guard x.isFinite else { return fixed(x, 0) }95        let f = NumberFormatter()96        f.locale = locale97        f.numberStyle = .percent98        f.minimumFractionDigits = decimals99        f.maximumFractionDigits = decimals100        return f.string(from: NSNumber(value: x)) ?? fixed(x * 100, decimals, locale: locale) + " %"101    }102103    public static func money(_ x: Double, locale: Locale = .current) -> String { fixed(x, 2, locale: locale) }104105    /// "< 0.0001" for tiny p-values, otherwise four decimals.106    public static func p(_ p: Double, locale: Locale = .current) -> String {107        guard p.isFinite else { return "—" }108        if p < 0.0001 { return "< " + fixed(0.0001, 4, locale: locale) }109        return fixed(p, 4, locale: locale)110    }111112    /// Degrees of freedom: integers without decimals, fractional df (Welch) with two.113    public static func df(_ d: Double, locale: Locale = .current) -> String {114        d == d.rounded() ? fixed(d, 0, locale: locale) : fixed(d, 2, locale: locale)115    }116117    public static func date(serial: Double, date1904: Bool = false) -> String {118        let c = DateSerial.components(serial, date1904: date1904)119        return String(format: "%04d-%02d-%02d", c.year, c.month, c.day)120    }121122    /// Text of a result value under a format.123    public static func text(_ v: Value, _ format: CellFormat = .auto, locale: Locale = .current) -> String {124        switch v {125        case .blank: return ""126        case .text(let s): return s127        case .number(let x):128            switch format {129            case .auto: return number(x, locale: locale)130            case .integer: return integer(x, locale: locale)131            case .fixed(let d): return fixed(x, d, locale: locale)132            case .percent(let d): return percent(x, d, locale: locale)133            case .money: return money(x, locale: locale)134            case .pValue: return p(x, locale: locale)135            case .scientific: return scientific(x, locale: locale)136            case .date: return date(serial: x)137            case .code: return number(x, locale: locale)138            }139        case .error(let e) where e == .na: return "—"140        default: return v.description141        }142    }143}144145public extension Value {146    /// Finite numbers become `.number`, everything else blank (for report grids).147    static func finite(_ d: Double?) -> Value {148        guard let d, d.isFinite else { return .blank }149        return .number(d)150    }151}152
Files main
Menu

Theme