c++negative-numberfmtzero-padding

Using {fmt}, zero padded numerical value are shorter when the value is negative, can I adapt this behavior?


I am using the {fmt} library to format strings and numeric values but I have problem with negative integers. When I pad the value with zeroes, I expect a consistent number of zero no matter the sign of the value.

For instance, using a padding of 4, I would like the following:

Here is an example:

#include <iostream>
#include "fmt/format.h"

int main()
{
    std::cout << fmt::format("{:04}", -2) << std::endl;
}

will output: -002

Is there a way to toggle this behaviour or a different way to zero-fill values to get my expected result?

Thanks for any help,


Solution

  • There's certainly nothing in the documentation for either fmt or Python's str.format (which fmt's syntax is based on). Both only state that padding is "sign-aware".

    This question asks for the same functionality for Python's str.format. The accepted answer there is to move the length to an argument, and make it one larger if the number is negative. Translating that to C++:

    for (auto x : { -2, 2 }) {
        fmt::print("{0:0{1}}\n", x, x < 0 ? 5 : 4 ); // prints -0002 and 0002
    }
    

    To break the format syntax down:

    {0:0{1}}
     │ │ └ position of the argument with the length
     │ └── "pad with zeros"
     └──── position of the argument with the value
    

    https://godbolt.org/z/5xz7T9