Skip to content

Conversation

@HydroH
Copy link
Contributor

@HydroH HydroH commented Mar 29, 2024

Closes #14436 .
This PR implemented following features:

  • Added an option to explicitly show + sign when formatting positive numbers;
  • When the fill character is 0 and number aligned to right, they will be recognized as leading zeroes, and the sign will be appended before the leading zeroes;
  • For hexadecimal floating point numbers, leading zeroes will be inserted after 0x.
    e.g.
try std.testing.expectFmt("  +1", "{:+>4}", .{1});
try std.testing.expectFmt("+001", "{:+0>4}", .{1});
try std.testing.expectFmt("+0x001p0", "{x:+0>8}", .{1.0});

Points worth discussing:

  • How to specify + as the fill character when the signed option is not present? Currently I use \\+ as the indentifier for such.
  • What should be the behaviour when formating inf and nan with leading zeroes and a sign? Currently the sign is still placed before leading zeroes.
    e.g.
try std.testing.expectFmt("1+++", "{:\\+<4}", .{1});
try std.testing.expectFmt("+00nan", "{:+0>6}", .{std.math.nan(f64)});

@xdBronch
Copy link
Contributor

what about putting the+ at the end to avoid the \\+? its a little messy and not straightforward when it actually is used for fill. e.g. {:0>4+}

@castholm
Copy link
Contributor

castholm commented Mar 29, 2024

This is just my opinion, but special-casing right-aligned zero fills feels like a bit of a hack and it's conflating generic alignment and numeric formatting which are two very different things. A user might want to zero-pad a signed number and still align that number separately, e.g.

// zero-pad integer part to 3 digits, print positive sign, left-align and fill with spaces to a min width of 10

|-000.100  |
|+010.333  |
|-097.167  |

It would be a major breaking change and probably worth discussing in a proposal issue before putting work in, but I think we should consider whether format specifiers should be updated to distinguish between generic alignment options and numeric formatting options. Perhaps something like {[argument][specifier]:[fill][alignment][width]#[+][min_integers].[precision]} could be used as starting point. For the example above the format string would then be {d: <10#+3.3}.

@andrewrk
Copy link
Member

andrewrk commented Jul 1, 2024

I don't know what to do with this. Perhaps we can reach a consensus over at #19488 and then decide.

@andrewrk
Copy link
Member

Sorry, it bitrotted before I got around to it.

@andrewrk andrewrk closed this Jul 17, 2025
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.

std.fmt.formatInt produces wrong strings depending on signedness of integers

4 participants