Skip to content

Commit 4c75230

Browse files
authored
fix(format): isolate special grouping rule to sign-aware zero-padding (RustPython#5924)
1 parent ef385a9 commit 4c75230

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

common/src/format.rs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,9 @@ impl FormatSpec {
436436
let sep = char::from(fg);
437437
let inter = self.get_separator_interval().try_into().unwrap();
438438
let magnitude_len = magnitude_str.len();
439-
let disp_digit_cnt = if self.fill == Some('0'.into()) {
439+
let disp_digit_cnt = if self.fill == Some('0'.into())
440+
&& self.align == Some(FormatAlign::AfterSign)
441+
{
440442
let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
441443
cmp::max(width, magnitude_len as i32)
442444
} else {
@@ -1323,6 +1325,45 @@ mod tests {
13231325
);
13241326
}
13251327

1328+
#[test]
1329+
fn test_format_int_width_and_grouping() {
1330+
// issue #5922: width + comma grouping should pad left, not inside the number
1331+
let spec = FormatSpec::parse("10,").unwrap();
1332+
let result = spec.format_int(&BigInt::from(1234)).unwrap();
1333+
assert_eq!(result, " 1,234"); // CPython 3.13.5
1334+
}
1335+
1336+
#[test]
1337+
fn test_format_int_padding_with_grouping() {
1338+
// CPython behavior: f'{1234:010,}' results in "00,001,234"
1339+
let spec1 = FormatSpec::parse("010,").unwrap();
1340+
let result1 = spec1.format_int(&BigInt::from(1234)).unwrap();
1341+
assert_eq!(result1, "00,001,234");
1342+
1343+
// CPython behavior: f'{-1234:010,}' results in "-0,001,234"
1344+
let spec2 = FormatSpec::parse("010,").unwrap();
1345+
let result2 = spec2.format_int(&BigInt::from(-1234)).unwrap();
1346+
assert_eq!(result2, "-0,001,234");
1347+
1348+
// CPython behavior: f'{-1234:=10,}' results in "- 1,234"
1349+
let spec3 = FormatSpec::parse("=10,").unwrap();
1350+
let result3 = spec3.format_int(&BigInt::from(-1234)).unwrap();
1351+
assert_eq!(result3, "- 1,234");
1352+
1353+
// CPython behavior: f'{1234:=10,}' results in " 1,234" (same as right-align for positive numbers)
1354+
let spec4 = FormatSpec::parse("=10,").unwrap();
1355+
let result4 = spec4.format_int(&BigInt::from(1234)).unwrap();
1356+
assert_eq!(result4, " 1,234");
1357+
}
1358+
1359+
#[test]
1360+
fn test_format_int_non_aftersign_zero_padding() {
1361+
// CPython behavior: f'{1234:0>10,}' results in "000001,234"
1362+
let spec = FormatSpec::parse("0>10,").unwrap();
1363+
let result = spec.format_int(&BigInt::from(1234)).unwrap();
1364+
assert_eq!(result, "000001,234");
1365+
}
1366+
13261367
#[test]
13271368
fn test_format_parse() {
13281369
let expected = Ok(FormatString {

0 commit comments

Comments
 (0)