xlformat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xlformat/__init__.py ADDED
@@ -0,0 +1,100 @@
1
+ """Apply Excel number-format strings to values and get the text Excel displays.
2
+
3
+ Pure Python, no runtime dependencies. ``format_value`` returns the plain string;
4
+ ``format_cell`` returns a ``FormattedCell`` with color, alignment, fill and overflow
5
+ information. ``NumberFormat.parse`` gives the compiled format. See ``ARCHITECTURE.md``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from xlformat._assemble import FormattedCell
11
+ from xlformat._errors import FormatError
12
+ from xlformat._measure import FontSpec, Measure
13
+ from xlformat._palette import DEFAULT_PALETTE
14
+ from xlformat._parser import NumberFormat, Section, SectionKind
15
+ from xlformat._quirks import Quirks
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ __all__ = [
20
+ "DEFAULT_PALETTE",
21
+ "FormatError",
22
+ "FormattedCell",
23
+ "NumberFormat",
24
+ "Quirks",
25
+ "Section",
26
+ "SectionKind",
27
+ "__version__",
28
+ "format_cell",
29
+ "format_value",
30
+ ]
31
+
32
+
33
+ def format_value(
34
+ value: object,
35
+ format_string: str = "General",
36
+ *,
37
+ width: int | None = None,
38
+ column_width: float | None = None,
39
+ font: FontSpec | None = None,
40
+ measure: Measure | None = None,
41
+ date1904: bool = False,
42
+ quirks: Quirks | None = None,
43
+ ) -> str:
44
+ """Return the text Excel displays for ``value`` under ``format_string``.
45
+
46
+ Args:
47
+ value: ``int``, ``float``, ``Decimal``, ``bool``, ``str``, ``None``, ``date``,
48
+ ``datetime``, ``time`` or ``timedelta``.
49
+ format_string: An Excel number format; ``""`` means ``General``.
50
+ width: Character mode: the width in characters, or ``None`` for the unconstrained
51
+ rendering (``*`` fills emit nothing, ``_x`` pads one space, overflow is 255 ``#``).
52
+ column_width: Excel mode: the column width in Column Width dialog units; the text is
53
+ measured with the glyph table of ``font`` as Excel for Mac does, so overflow, ``#``
54
+ and fill counts and General digit reduction match the sheet. Not with ``width``.
55
+ font: The cell's font for Excel mode, a name or ``(name, size)``; default
56
+ ``("Calibri", 11)``, openpyxl's workbook default. Only Calibri is bundled (measured
57
+ at 9, 10, 11, 12, 14 and 16 points, scaled from the nearest measured size
58
+ elsewhere); other names raise ``LookupError``. Glyphs outside the table measure as
59
+ a digit.
60
+ measure: A custom text measure for ``width``, whose units then also apply to ``width``.
61
+ date1904: Use the 1904 date system for dates and serials.
62
+ quirks: Which Excel quirks to reproduce; ``None`` means ``Quirks.EXCEL``.
63
+
64
+ Raises:
65
+ FormatError: The format string is one Excel refuses to open from a file.
66
+ TypeError: ``value`` has an unsupported type.
67
+ ValueError: ``value`` is NaN or infinite.
68
+ """
69
+ return NumberFormat.parse(format_string).format(
70
+ value,
71
+ width=width,
72
+ column_width=column_width,
73
+ font=font,
74
+ measure=measure,
75
+ date1904=date1904,
76
+ quirks=quirks,
77
+ )
78
+
79
+
80
+ def format_cell(
81
+ value: object,
82
+ format_string: str = "General",
83
+ *,
84
+ width: int | None = None,
85
+ column_width: float | None = None,
86
+ font: FontSpec | None = None,
87
+ measure: Measure | None = None,
88
+ date1904: bool = False,
89
+ quirks: Quirks | None = None,
90
+ ) -> FormattedCell:
91
+ """Like :func:`format_value` but return a :class:`FormattedCell` with display details."""
92
+ return NumberFormat.parse(format_string).format_cell(
93
+ value,
94
+ width=width,
95
+ column_width=column_width,
96
+ font=font,
97
+ measure=measure,
98
+ date1904=date1904,
99
+ quirks=quirks,
100
+ )
xlformat/_assemble.py ADDED
@@ -0,0 +1,134 @@
1
+ """Turn render pieces into text and a ``FormattedCell``, applying the width decision.
2
+
3
+ ``ARCHITECTURE.md`` section 8: both width modes are a measure function plus a width in its
4
+ units. A ``*`` fill repeats its character until the text measures the width (the last fill in a
5
+ section wins); ``_x`` pads measure as one space; ``General`` reduces its digits before it
6
+ overflows; numbers, dates and booleans that still do not fit become a run of ``#`` that fills
7
+ the width, text never does.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from decimal import Decimal
14
+ from typing import Literal
15
+
16
+ from xlformat._measure import Measure, character_measure, general_cost
17
+ from xlformat._number import general_text_fitting
18
+ from xlformat._parser import Piece
19
+
20
+ Align = Literal["left", "right", "center"]
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class FormattedCell:
25
+ """What Excel shows for one cell: the text and the display information around it.
26
+
27
+ Attributes:
28
+ text: What the cell shows under the given width.
29
+ full_text: The width-less rendering (what copy and paste gives); always set.
30
+ color: Section color, ``'Red'`` ... ``'Color56'``, or ``None``.
31
+ align: Excel's default horizontal alignment for the value kind.
32
+ fill: ``(index, char)`` of a ``*`` fill in ``text``, or ``None``.
33
+ overflow: True when ``text`` is a run of ``#``.
34
+ """
35
+
36
+ text: str
37
+ full_text: str
38
+ color: str | None
39
+ align: Align
40
+ fill: tuple[int, str] | None
41
+ overflow: bool
42
+
43
+
44
+ OVERFLOW_WIDTH = 255 # Excel's widest column; the clipboard shows this many '#'
45
+
46
+
47
+ def _hashes(width: float | None, measure: Measure) -> str:
48
+ if width is None:
49
+ return "#" * OVERFLOW_WIDTH
50
+ return "#" * max(int(width // measure("#")), 1)
51
+
52
+
53
+ def overflow(
54
+ color: str | None,
55
+ width: float | None = None,
56
+ full_text: str | None = None,
57
+ measure: Measure = character_measure,
58
+ ) -> FormattedCell:
59
+ """A value the section cannot show: a ``#`` run filling the width (255 without a width)."""
60
+ text = _hashes(width, measure)
61
+ # full_text is always the width-less rendering: 255 '#' for a value the section cannot show
62
+ full = _hashes(None, measure) if full_text is None else full_text
63
+ return FormattedCell(text, full, color, "right", None, True)
64
+
65
+
66
+ def _join(pieces: list[Piece], general: str | None) -> tuple[str, tuple[int, str] | None]:
67
+ """Text with pads as one space and fills left out; the last fill's position and character."""
68
+ parts: list[str] = []
69
+ position = 0
70
+ fill: tuple[int, str] | None = None
71
+ for kind, text in pieces:
72
+ if kind == "pad":
73
+ parts.append(" ")
74
+ position += 1
75
+ elif kind == "fill":
76
+ fill = (position, text) # Excel honors the last fill in a section
77
+ else:
78
+ piece = general if (kind == "general" and general is not None) else text
79
+ parts.append(piece)
80
+ position += len(piece)
81
+ return "".join(parts), fill
82
+
83
+
84
+ def assemble(
85
+ pieces: list[Piece],
86
+ color: str | None,
87
+ align: Align,
88
+ *,
89
+ width: float | None = None,
90
+ measure: Measure = character_measure,
91
+ overflows: bool = True,
92
+ general_value: Decimal | None = None,
93
+ units: float | None = None,
94
+ ) -> FormattedCell:
95
+ """Join pieces and apply the width decision.
96
+
97
+ ``general_value`` is the number behind a ``general`` piece, for digit reduction, which
98
+ Excel does by characters against the column width in ``units`` (``general_cost``), not by
99
+ glyph widths; ``overflows`` is False for text, which never becomes a ``#`` run.
100
+ """
101
+ full_text, fill = _join(pieces, None)
102
+ if width is None:
103
+ return FormattedCell(full_text, full_text, color, align, fill, False)
104
+ general: str | None = None
105
+ has_general = general_value is not None and any(k == "general" for k, _ in pieces)
106
+ if has_general:
107
+ assert general_value is not None
108
+ # The General token's budget is the column width in units less what the literals (and
109
+ # the sign) take, in digit units of this measure: '( ' and ' )' cost 1.67 in Excel mode
110
+ # and 4 in character mode. The number itself is counted by characters (general_cost).
111
+ total_units = width if units is None else units
112
+ digit = measure("0")
113
+ rest, _ = _join([p for p in pieces if p[0] != "general"], None)
114
+ unsigned, _ = _join([p for p in pieces if p[0] not in ("general", "sign")], None)
115
+ budget = total_units - measure(rest) / digit
116
+ sci_budget = total_units - measure(unsigned) / digit if rest else None
117
+ general = general_text_fitting(general_value, budget, general_cost, sci_budget)
118
+ if general is None:
119
+ return overflow(color, width, full_text, measure)
120
+ if general.strip("-") == "0":
121
+ # a negative whose General reduced to zero drops its sign: General"x" with -0.001
122
+ # at width 6 shows "0x" (numeric_core_width)
123
+ pieces = [p for p in pieces if p[0] != "sign"]
124
+ text, fill = _join(pieces, general)
125
+ if fill is not None:
126
+ count = int((width - measure(text)) // measure(fill[1]))
127
+ if count > 0:
128
+ position, char = fill
129
+ text = text[:position] + char * count + text[position:]
130
+ else:
131
+ fill = None
132
+ if overflows and not has_general and measure(text) > width:
133
+ return overflow(color, width, full_text, measure)
134
+ return FormattedCell(text, full_text, color, align, fill, False)
xlformat/_datetime.py ADDED
@@ -0,0 +1,253 @@
1
+ """Date and time rendering. See ``ARCHITECTURE.md`` section 7 and ``QUIRKS.md``.
2
+
3
+ The serial is taken as a double (Excel's own representation, not the 15-digit display value).
4
+ Excel's clock arithmetic, reproduced here operation for operation (``CAPTURING.md`` section 2
5
+ item 15; 41,266 captured rows, no misses): the serial is biased by half of the finest displayed
6
+ unit (a second, or a tenth, hundredth or thousandth of one; never coarser), then day, hour,
7
+ minute and second are peeled from successive fractions, each multiplied up and truncated. The
8
+ carry therefore propagates into the day, and the floating-point noise of the peel is Excel's
9
+ own: a ``General`` token inside a date section leaks the biased seconds before truncation
10
+ (``0.499999803`` for serial 44927). Elapsed codes come from the biased total seconds. Civil
11
+ dates come from integer arithmetic over the day number, never from ``datetime`` objects, so
12
+ January 0 and February 29, 1900 need no special objects.
13
+
14
+ Sections made only of elapsed codes (``[h]``, ``[mm]``, ``[s]``) have no upper limit and show
15
+ negative values with a leading minus; other sections show ``#`` for negatives in the 1900
16
+ system, while the 1904 system shows a minus sign followed by the rendering of the magnitude.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from decimal import Decimal
23
+
24
+ from xlformat._number import general_text
25
+ from xlformat._parser import NumberFormat, Piece, Section, Token, TokenKind
26
+ from xlformat._quirks import Quirks
27
+ from xlformat._values import limit_precision
28
+
29
+ _MONTHS = (
30
+ "January",
31
+ "February",
32
+ "March",
33
+ "April",
34
+ "May",
35
+ "June",
36
+ "July",
37
+ "August",
38
+ "September",
39
+ "October",
40
+ "November",
41
+ "December",
42
+ )
43
+ _DAYS = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
44
+ _SECONDS_PER_DAY = 86400
45
+ _DAY_RECIPROCAL = 1 / 86400 # Excel forms the total seconds as x / (1/86400), not x * 86400
46
+ _MAX_DAY_1900 = 2958465 # 9999-12-31
47
+ _DAYS_1900_TO_1904 = 1462
48
+ SYSTEM_DATE = "dddd, mmmm d, yyyy"
49
+ SYSTEM_TIME = "h:mm:ss AM/PM"
50
+ _SYSTEM_DATE_TAGS = {"x-sysdate", "f800"}
51
+ _SYSTEM_TIME_TAGS = {"x-systime", "f400"}
52
+
53
+
54
+ def days_from_civil(y: int, m: int, d: int) -> int:
55
+ """Day count from 0000-03-01 for a proleptic Gregorian date (inverse of civil_from_days)."""
56
+ y -= m <= 2
57
+ era = (y if y >= 0 else y - 399) // 400
58
+ yoe = y - era * 400
59
+ doy = (153 * (m + (-3 if m > 2 else 9)) + 2) // 5 + d - 1
60
+ doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
61
+ return era * 146097 + doe
62
+
63
+
64
+ def civil_from_days(z: int) -> tuple[int, int, int]:
65
+ """Proleptic Gregorian (year, month, day) for a day count from 0000-03-01."""
66
+ era = (z if z >= 0 else z - 146096) // 146097
67
+ doe = z - era * 146097
68
+ yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365
69
+ y = yoe + era * 400
70
+ doy = doe - (365 * yoe + yoe // 4 - yoe // 100)
71
+ mp = (5 * doy + 2) // 153
72
+ d = doy - (153 * mp + 2) // 5 + 1
73
+ m = mp + 3 if mp < 10 else mp - 9
74
+ return (y + 1 if m <= 2 else y, m, d)
75
+
76
+
77
+ _EPOCH_1900 = days_from_civil(1899, 12, 30) # serial 61 = 1900-03-01 under this epoch
78
+ _EPOCH_1904 = days_from_civil(1904, 1, 1)
79
+
80
+
81
+ def calendar(day: int, date1904: bool, quirks: Quirks) -> tuple[int, int, int, int]:
82
+ """(year, month, day, weekday with Sunday = 0) for an Excel day number."""
83
+ if date1904:
84
+ y, m, d = civil_from_days(_EPOCH_1904 + day)
85
+ return y, m, d, (day + 5) % 7
86
+ weekday = (day + 6) % 7
87
+ if quirks.leap_year_1900:
88
+ if day == 0:
89
+ return 1900, 1, 0, weekday
90
+ if day == 60:
91
+ return 1900, 2, 29, weekday
92
+ if day < 60:
93
+ y, m, d = civil_from_days(_EPOCH_1900 + 1 + day)
94
+ return y, m, d, weekday
95
+ y, m, d = civil_from_days(_EPOCH_1900 + day)
96
+ return y, m, d, weekday
97
+
98
+
99
+ def _fraction_digits(tokens: tuple[Token, ...]) -> int:
100
+ """Fractional-second digits displayed (0 to 3). Excel always rounds to at least the second."""
101
+ digits = 0
102
+ for t in tokens:
103
+ if t.kind is TokenKind.DATE and "." in t.text:
104
+ digits = max(digits, len(t.text.partition(".")[2]))
105
+ return digits
106
+
107
+
108
+ def _system_tokens(section: Section) -> tuple[Token, ...]:
109
+ """Tokens of the system date or time format when the section carries that tag."""
110
+ tag = (section.locale or "").lower()
111
+ if tag in _SYSTEM_DATE_TAGS:
112
+ return NumberFormat.parse(SYSTEM_DATE).sections[0].tokens
113
+ if tag in _SYSTEM_TIME_TAGS:
114
+ return NumberFormat.parse(SYSTEM_TIME).sections[0].tokens
115
+ return section.tokens
116
+
117
+
118
+ def render_datetime(
119
+ section: Section,
120
+ serial: float,
121
+ display: Decimal,
122
+ *,
123
+ date1904: bool,
124
+ quirks: Quirks,
125
+ ) -> list[Piece] | None:
126
+ """Pieces for a date/time section, or ``None`` when the value cannot be shown.
127
+
128
+ ``serial`` is the double Excel works from; ``display`` is the 15-digit value, which Excel
129
+ does not use for clock arithmetic.
130
+ """
131
+ del display
132
+ tokens = _system_tokens(section)
133
+ elapsed_only = all(
134
+ t.kind not in (TokenKind.DATE, TokenKind.MINUTE, TokenKind.AMPM) for t in tokens
135
+ ) and any(t.kind is TokenKind.ELAPSED for t in tokens)
136
+ negative = serial < 0
137
+ if negative and not (date1904 or elapsed_only):
138
+ return None # decided on the raw sign: -1e-9 shows '#', not January 0, 1900
139
+ x = abs(serial)
140
+ digits = _fraction_digits(tokens)
141
+ scale = 10**digits
142
+ bias = 0.5 / scale # half of the displayed unit, in seconds
143
+ # Excel's arithmetic (module docstring): bias the serial, then peel and truncate. Every
144
+ # operation and its order matter: the 59.5-second rows separate x / (1/86400) from
145
+ # x * 86400, and the day-44927 rows separate the bias in days from a bias in seconds.
146
+ d = x + bias / _SECONDS_PER_DAY
147
+ day = math.floor(d)
148
+ h = (d - day) * 24
149
+ hour = math.floor(h)
150
+ m = (h - hour) * 60
151
+ minute = math.floor(m)
152
+ biased_seconds = (m - minute) * 60
153
+ second = math.floor(biased_seconds)
154
+ frac = math.floor((biased_seconds - second) * scale)
155
+ elapsed = x / _DAY_RECIPROCAL + bias
156
+ limit = _MAX_DAY_1900 - (_DAYS_1900_TO_1904 if date1904 else 0)
157
+ if day > limit and not elapsed_only:
158
+ return None
159
+ has_ampm = any(t.kind is TokenKind.AMPM for t in tokens)
160
+ year = month = dom = weekday = 0
161
+ if any(t.kind is TokenKind.DATE and t.text[0] in "ymde" for t in tokens):
162
+ year, month, dom, weekday = calendar(day, date1904, quirks)
163
+ out: list[Piece] = [("lit", "-")] if negative else []
164
+ for t in tokens:
165
+ k = t.kind
166
+ if k is TokenKind.DATE:
167
+ out.append(
168
+ (
169
+ "lit",
170
+ _date_field(
171
+ t.text, year, month, dom, weekday, hour, second, frac, digits, has_ampm
172
+ ),
173
+ )
174
+ )
175
+ elif k is TokenKind.MINUTE:
176
+ out.append(("lit", f"{minute:02d}" if t.text == "mm" else str(minute)))
177
+ elif k is TokenKind.AMPM:
178
+ out.append(("lit", _ampm(t.text, hour)))
179
+ elif k is TokenKind.ELAPSED:
180
+ whole = math.floor(elapsed / {"h": 3600, "m": 60, "s": 1}[t.text[0]])
181
+ out.append(("lit", str(whole).zfill(len(t.text))))
182
+ elif k is TokenKind.PAD:
183
+ out.append(("pad", t.text))
184
+ elif k is TokenKind.FILL:
185
+ out.append(("fill", t.text))
186
+ elif k is TokenKind.CURRENCY:
187
+ if t.text:
188
+ out.append(("lit", t.text))
189
+ elif k in (TokenKind.COLOR, TokenKind.CONDITION):
190
+ continue
191
+ elif k is TokenKind.GENERAL:
192
+ # Excel leaks its biased seconds before truncation, noise included (a whole day
193
+ # shows "0.5"; serial 44927 shows "0.499999803").
194
+ out.append(("lit", general_text(limit_precision(Decimal(biased_seconds)))))
195
+ else:
196
+ out.append(("lit", t.text))
197
+ return out
198
+
199
+
200
+ def _ampm(token: str, hour: int) -> str:
201
+ pm = hour >= 12
202
+ if len(token) == 3: # A/P keeps the token's case; AM/PM is always upper-case (datetime suite)
203
+ text = "P" if pm else "A"
204
+ return text.lower() if token.islower() else text
205
+ return "PM" if pm else "AM"
206
+
207
+
208
+ def _date_field(
209
+ code: str,
210
+ year: int,
211
+ month: int,
212
+ dom: int,
213
+ weekday: int,
214
+ hour: int,
215
+ second: int,
216
+ frac: int,
217
+ digits: int,
218
+ has_ampm: bool,
219
+ ) -> str:
220
+ c = code[0]
221
+ if c == "y":
222
+ return f"{year % 100:02d}" if code == "yy" else f"{year:04d}"
223
+ if c == "e":
224
+ return f"{year:04d}"
225
+ if c == "m":
226
+ if code == "m":
227
+ return str(month)
228
+ if code == "mm":
229
+ return f"{month:02d}"
230
+ name = _MONTHS[month - 1]
231
+ if code == "mmm":
232
+ return name[:3]
233
+ if code == "mmmm":
234
+ return name
235
+ return name[0]
236
+ if c == "d":
237
+ if code == "d":
238
+ return str(dom)
239
+ if code == "dd":
240
+ return f"{dom:02d}"
241
+ name = _DAYS[weekday]
242
+ return name[:3] if code == "ddd" else name
243
+ if c == "h":
244
+ h = hour
245
+ if has_ampm:
246
+ h = hour % 12 or 12
247
+ return f"{h:02d}" if code == "hh" else str(h)
248
+ # seconds, possibly with a fraction
249
+ whole, _, fraction = code.partition(".")
250
+ text = f"{second:02d}" if whole == "ss" else str(second)
251
+ if fraction:
252
+ text += "." + str(frac).zfill(digits)[: len(fraction)]
253
+ return text
xlformat/_errors.py ADDED
@@ -0,0 +1,12 @@
1
+ """Exceptions raised by xlformat."""
2
+
3
+
4
+ class FormatError(ValueError):
5
+ """The format string is one Excel refuses to open from a file.
6
+
7
+ Raised only for strings Excel itself cannot render, where the file would need repair, such
8
+ as a lower-case ``e+`` after digits or five sections. Strings that Excel's Format Cells
9
+ dialog rejects but a file may contain render as Excel renders them. Callers that read files
10
+ typically catch it and fall back to ``General``, which is what Excel's repair does to the
11
+ cell. It is a subclass of ``ValueError``.
12
+ """
xlformat/_fraction.py ADDED
@@ -0,0 +1,186 @@
1
+ """Fraction sections (``# ?/?``, ``# ??/16``). See ``ARCHITECTURE.md`` section 6 and ``QUIRKS.md``.
2
+
3
+ Excel's denominator search for free denominators is a continued-fraction expansion stopped at
4
+ an epsilon, run on the double, not the closest fraction; ``fraction_denominators`` off uses
5
+ ``Fraction.limit_denominator``. The fixed-denominator numerator is Excel's nudged half-up in
6
+ double arithmetic (``fixed_numerator``), zero misses on every captured row.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from decimal import ROUND_HALF_DOWN, ROUND_HALF_UP, Decimal
13
+ from fractions import Fraction
14
+
15
+ from xlformat._number import render_number
16
+ from xlformat._parser import FractionSpec, NumberSpec, Piece
17
+ from xlformat._quirks import Quirks
18
+
19
+ _NUDGE = 1.0 + 2.0**-52 # 1 + DBL_EPSILON, exactly representable
20
+
21
+
22
+ def excel_fraction(value: float, max_denominator: int) -> Fraction:
23
+ """Excel's continued-fraction search.
24
+
25
+ Adopted from ExcelNumberFormat; confirmed by the 2023 capture for one- to three-digit
26
+ denominators.
27
+ """
28
+ b = value
29
+ p2, p1, q2, q1 = 0.0, 1.0, 1.0, 0.0
30
+ p = q = 0.0
31
+ while q1 < max_denominator:
32
+ a = math.floor(b)
33
+ p = a * p1 + p2
34
+ q = a * q1 + q2
35
+ if (b - a) < 0.00000005:
36
+ break
37
+ b = 1 / (b - a)
38
+ p2, p1, q2, q1 = p1, p, q1, q
39
+ if q > max_denominator:
40
+ if q1 > max_denominator:
41
+ p, q = p2, q2
42
+ else:
43
+ p, q = p1, q1
44
+ return Fraction(int(p), int(q))
45
+
46
+
47
+ def fixed_numerator(value: Decimal, denominator: int) -> int:
48
+ """Numerator for a fixed denominator, as Excel computes it.
49
+
50
+ ``value`` is the non-negative value (a double, possibly scaled by percent signs, as a
51
+ Decimal); the result is the numerator of the whole value, ``W * D + n``.
52
+
53
+ The rule (``CAPTURING.md`` section 2 item 22; found with a larger capture of half-step values,
54
+ included as ``fraction_threshold`` and ``fraction_random``; every
55
+ fixed-denominator captured row, 38,904 of them across ``fraction``, ``fraction_ties``,
56
+ ``fraction_threshold``, ``fraction_random``, ``capture2023`` and ``capture2026``, zero
57
+ misses): the fraction part of the double is scaled up by one relative epsilon,
58
+ ``f' = fl(f * (1 + 2**-52))``, the product ``t = fl(f' * D)`` is formed in double
59
+ arithmetic, and the numerator is ``floor(t)`` plus one when ``t - floor(t) >= 0.5``.
60
+ Phrasing the half-up as ``floor(t + 0.5)`` is wrong at k = 0, where ``t + 0.5`` rounds up to
61
+ 1 for ``t`` within a quarter ulp of 0.5.
62
+
63
+ The constant is DBL_EPSILON exactly: the window is (0.995, 1.005) * 2**-52, bounded below
64
+ by 0.7504999999999997 under ``# ???/1000`` (Excel rounds up) and above by
65
+ 0.09374999999999997 under ``# ??/16`` (Excel rounds down); 2**-53 misses 172 rows and
66
+ 2**-51 misses 377. The nudge is applied to the fraction part, not the whole value (rows with
67
+ whole parts 1 and 12 decide like their whole-part-0 twins; nudging ``x`` misses 105), and
68
+ before the product, not after (misses 52); dividing by ``1 / D`` misses 29.
69
+
70
+ Why it looked like a tolerance: for a fraction part with mantissa ``m`` in [1, 2), the nudge
71
+ adds ``round(m)`` ulps, one below ``m = 1.5`` and two above, so a deficit of two ulps below
72
+ the half step rounds up only in the upper half of each binade; no tolerance relative to the
73
+ half step, the value or the denominator fitted every row.
74
+ """
75
+ x = float(value)
76
+ whole = math.floor(x)
77
+ fraction = x - whole # exact: the fractional bits of x
78
+ scaled = fraction * _NUDGE * denominator # two roundings, left to right, as Excel's C code
79
+ n = math.floor(scaled)
80
+ if scaled - n >= 0.5:
81
+ n += 1
82
+ return whole * denominator + n
83
+
84
+
85
+ def fraction_value(raw: float) -> Decimal:
86
+ """The value fractions work from: the exact double, as a Decimal.
87
+
88
+ An earlier version rounded it to 15 significant digits; the recapture with exact number
89
+ texts showed the step changes nothing (CAPTURING.md section 2 item 18).
90
+ """
91
+ return Decimal(abs(raw))
92
+
93
+
94
+ _MAX_NUMERATOR = 2**31 - 1 # a larger numerator shows '#' (fraction suite: 49382715605/4)
95
+
96
+
97
+ def render_fraction(
98
+ spec: FractionSpec, raw: float, negative: bool, quirks: Quirks
99
+ ) -> list[Piece] | None:
100
+ """Pieces for a fraction section, or ``None`` when the numerator overflows 32 bits.
101
+
102
+ ``raw`` is the double (sign ignored).
103
+ """
104
+ v = fraction_value(raw)
105
+ x = float(v)
106
+ for _ in range(spec.percent):
107
+ x *= 100.0 # in double arithmetic, as Excel does (1234567.891 under ?/?% is 1111111102/9)
108
+ if spec.fixed_denominator and quirks.fraction_denominators:
109
+ frac = Fraction(fixed_numerator(Decimal(x), spec.fixed_denominator), spec.fixed_denominator)
110
+ elif spec.fixed_denominator:
111
+ # the closest fraction with this denominator: plain half-up on the exact product
112
+ n = int((Decimal(x) * spec.fixed_denominator).quantize(Decimal(1), rounding=ROUND_HALF_UP))
113
+ frac = Fraction(n, spec.fixed_denominator)
114
+ elif quirks.fraction_denominators:
115
+ frac = excel_fraction(x, 10 ** len(spec.denominator) - 1)
116
+ else:
117
+ frac = Fraction(x).limit_denominator(10 ** len(spec.denominator) - 1)
118
+ whole = 0
119
+ if spec.whole is not None:
120
+ whole = math.floor(frac)
121
+ frac -= whole
122
+ if x > 99_999_999_999_999: # 15+ integer digits: Excel rounds half down here
123
+ whole = int(Decimal(x).quantize(Decimal(1), rounding=ROUND_HALF_DOWN))
124
+ numerator, denominator = frac.numerator, frac.denominator
125
+ if spec.fixed_denominator:
126
+ numerator = numerator * (spec.fixed_denominator // denominator)
127
+ denominator = spec.fixed_denominator
128
+ if numerator > _MAX_NUMERATOR:
129
+ return None
130
+ show_fraction = spec.whole is None or "0" in spec.numerator
131
+ out: list[Piece] = []
132
+ if negative and not (spec.whole is None and numerator == 0):
133
+ out.append(("lit", "-")) # a bare zero fraction drops the sign ('0/1' for -0.0001)
134
+ out.extend(spec.leading)
135
+ if spec.whole is not None:
136
+ whole_digits = [p[1] for p in spec.whole.integer if p[0] == "digit"]
137
+ if whole == 0 and "0" not in whole_digits and "0" in spec.numerator:
138
+ pass # '# 0/0' with 0.125 shows '1/8', with 0 shows '0/1': whole part and space vanish
139
+ elif whole == 0 and frac == 0:
140
+ # the whole value is zero: Excel shows a 0 even for '#' placeholders ('0 ')
141
+ out.extend(_forced_zero(spec.whole))
142
+ out.extend(spec.whole_trailing)
143
+ else:
144
+ out.extend(render_number(spec.whole, Decimal(whole), False))
145
+ out.extend(spec.whole_trailing)
146
+ if frac or show_fraction:
147
+ n_text = str(numerator)
148
+ if "0" in spec.numerator:
149
+ n_text = n_text.rjust(len(spec.numerator), "0")
150
+ elif "?" in spec.numerator:
151
+ n_text = n_text.rjust(len(spec.numerator), " ")
152
+ d_text = str(denominator)
153
+ if not spec.fixed_denominator:
154
+ if "0" in spec.denominator:
155
+ d_text = d_text.rjust(len(spec.denominator), "0")
156
+ elif "?" in spec.denominator:
157
+ d_text = d_text.ljust(len(spec.denominator), " ")
158
+ out.append(("lit", n_text))
159
+ out.extend(spec.slash)
160
+ out.append(("lit", d_text))
161
+ elif "?" in spec.numerator:
162
+ out.append(("lit", " " * len(spec.numerator)))
163
+ out.extend(
164
+ ("lit", " " * len(text)) if kind == "lit" else (kind, text) for kind, text in spec.slash
165
+ )
166
+ out.append(("lit", " " * len(spec.denominator)))
167
+ out.extend(spec.trailing)
168
+ return out
169
+
170
+
171
+ def _forced_zero(whole: NumberSpec) -> list[Piece]:
172
+ """Render a zero whole part with its last placeholder forced to show a digit."""
173
+ last = max(i for i, p in enumerate(whole.integer) if p[0] == "digit")
174
+ forced = NumberSpec(
175
+ leading=whole.leading,
176
+ integer=tuple(("digit", "0") if i == last else p for i, p in enumerate(whole.integer)),
177
+ decimal=whole.decimal,
178
+ trailing=whole.trailing,
179
+ has_point=whole.has_point,
180
+ grouping=whole.grouping,
181
+ scale=whole.scale,
182
+ percent=whole.percent,
183
+ n_integer=whole.n_integer,
184
+ n_decimal=whole.n_decimal,
185
+ )
186
+ return render_number(forced, Decimal(0), False)