[英]Using fmtlib, zero padded numerical value are shorter when the value is negative, can I adapt this behaviour?
I am using fmtlib to format strings and numeric values but I have problem with negative integers.我正在使用fmtlib来格式化字符串和数值,但我对负整数有问题。 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:例如,使用 4 的填充,我想要以下内容:
fmtlib's default behaviour is to take into account a prefix lenght (ie the sign "-") into the padded length which means that -2 is returned as "-002" fmtlib 的默认行为是在填充长度中考虑前缀长度(即符号“-”),这意味着 -2 返回为“-002”
Here is an example:下面是一个例子:
#include <iostream>
#include "fmt/format.h"
int main()
{
std::cout << fmt::format("{:04}", -2) << std::endl;
}
will output: -002
将输出:
-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). fmt 或 Python 的
str.format
(fmt 的语法基于)的文档中肯定没有任何内容。 Both only state that padding is "sign-aware".两者都只说明填充是“符号感知”的。
This question asks for the same functionality for Python's str.format
.这个问题要求 Python 的
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++:
将其转换为 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.