gpt4 book ai didi

c++ - 将 double 转换为固定宽度的字符串

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:44 26 4
gpt4 key购买 nike

我想将 double 型转换为固定宽度的字符串。

如果宽度为 10,那么我希望 double 值四舍五入到这个宽度。

例如,如果value = 102.121323435345,width为10,那么这个值应该是,

position==>        0123456789                  value = 102.121323

I can achieve this with snprintf, but I am looking for a c++ native code to do the same.


char buf[125];
snprint(buf, width, "%.6f", value);

我尝试使用下面的,但它对我帮助不大,

 
std::ostringstream oss;
oss << std::fixed << std::setw(10) << std::precision(6) << value;

std::setw 保证值的最小宽度,如果值大于宽度大小,它不会对值进行四舍五入。

谢谢。

最佳答案

您可以像这样使用 osteram::widthostream::precision 函数来实现您的目标

std::ostringstream out;
out.width(10);
out.precision(10);
out << 123.12345678910111213;

虽然它不会在点后添加零以尊重宽度,但它会在数字前添加空格(或您选择的任何字符)。因此,如果您将 102 作为输入值传递,您将得到“102”或“0000000102”(如果您调用 out.fill('0');)而不是“102.000000”。

关于c++ - 将 double 转换为固定宽度的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com