Skip to content

Clamp rounded fractional seconds to the field width#1292

Open
vineethsaivs wants to merge 1 commit into
python-babel:masterfrom
vineethsaivs:fix/frac-seconds-field-overflow
Open

Clamp rounded fractional seconds to the field width#1292
vineethsaivs wants to merge 1 commit into
python-babel:masterfrom
vineethsaivs:fix/frac-seconds-field-overflow

Conversation

@vineethsaivs

Copy link
Copy Markdown

DateTimeFormat.format_frac_seconds can render a fractional-seconds field that is wider than its declared number of digits.

The method rounds the microseconds to the requested precision:

value = self.value.microsecond / 1000000
return self.format(round(value, num) * 10**num, num)

round(value, num) can carry up to a whole second (for example 0.999 rounds to 1.0). Then 1.0 * 10**num == 10**num, which has num + 1 digits, and self.format ('%0*d' % (num, value)) prints all of them. Babel intentionally does not carry into the seconds field, so the fractional field simply overflows its width.

from datetime import time
from babel.dates import DateTimeFormat

DateTimeFormat(time(1, 2, 3, 990000), locale='en_US')['S']    # '10'  (expected '9')
DateTimeFormat(time(1, 2, 3, 999500), locale='en_US')['SS']   # '100' (expected '99')

A single S digit must be 0 to 9, but it can render 10.

Fix: clamp the rounded value to the largest in-field value so it stays within the declared width:

frac = min(int(round(value, num) * 10**num), 10**num - 1)
return self.format(frac, num)

This only changes the overflow case (the value is clamped to all nines, the closest representation without carrying into seconds). Every existing test_fractional_seconds expectation, including the deliberately rounded ['SSSS'] == '0346', is unchanged. Added a regression test covering the S, SS, and SSSS overflow inputs.

format_frac_seconds rounds the microseconds to the requested number of
digits, but the rounding can carry up to a whole second (0.999 -> 1.0),
producing a value with one digit too many. self.format then prints all of
them, overflowing the fractional field (S rendered '10', SS rendered '100').
Clamp the rounded value to the maximum in-field value so it stays within the
declared width.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant