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,
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++:To break the format syntax down:
https://godbolt.org/z/5xz7T9