![](/img/trans.png)
[英]How to format floating point numbers with decimal comma using the fmt library?
[英]Cannot format two floating point numbers in one string using the {fmt} library
我刚开始在我的应用程序中使用{fmt}
库,发现我无法使用该库来格式化具有不同位数的两个浮点数,因为程序崩溃了。
经过一些实验,我意识到它实际上有点糟糕,因为在我用{0:.0f}
(或0:.2f
,就此而言)格式化任何浮点数后,我无法格式化任何东西。
对我来说违反直觉的代码示例:
#include <fmt\core.h>
#include <iostream>
int main()
{
std::cout << fmt::format("{} , {}\n", 3.14, 10.0); // Prints out '3.14, 10.0'
//std::cout << fmt::format("{0:.0f} , {}\n", 3.14, 10.0); // - ERROR: fmt::v6::format_error at memory location
std::cout << fmt::format("{0:.0f} , {0:.0f}\n", 3.14, 10.0); // - WRONG RESULT: Prints out '3, 3'
std::cout << fmt::format("{0:.0f} , {:d}\n", 3.14, 10); // ERROR: fmt::v6::format_error at memory location
//std::cout << fmt::format("{:s}, {:s}", fmt::format("{0:.2f}", 3.14), fmt::format("{:0:.1f}", 10.0)); // EVEN THIS DOESN'T WORK
// This is the only way I found of getting the output I want:
std::string a = fmt::format("{0:.2f}", 3.14);
std::string b = fmt::format("{0:.1f}", 10.0);
std::cout << fmt::format("{:s}, {:s}", a, b);
return 0;
}
:
之前的数字用于计算参数。
0:
是第一个, 1:
第二个……
如果您没有在:
之前放置任何内容,则将按顺序考虑参数。
您不能在相同格式的字符串中混合一些{}
与参数计数器和其他没有这样的参数计数器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.