Using fmtlib, zero padded numerical value are shorter when the value is negative, can I adapt this behaviour?

4k views Asked by At

I am using fmtlib 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:

  • 2 to be returned as "0002"
  • -2 to be returned as "-0002"

fmtlib's default behaviour is to take into account a prefix lenght (i.e. the sign "-") into the padded length which means that -2 is returned as "-002"

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,

1

There are 1 answers

1
parktomatomi On BEST ANSWER

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