c++ - 使用 stringstream 精度格式化 float 但丢弃零填充

标签 c++ stringstream

我正在尝试将 float 和长 double 的精度(即小数位数)设置为 10,但我不希望它们用零填充。即,

123456.789123456789 应该给出 123456.7891234568,但是 123456 不应该给出 123456.0000000000,而是 123456

到目前为止,我已经将范围缩小到:

long double myNumber;
string myString;
ostringstream myStream;
myStream.setf(ios::fixed,ios::floatfield);
myStream.precision(10);
myStream << myNumber;
myString = myStream.str();

我也试过摆弄 setfill(' ') 和 std::ws 但无法真正掌握它。 有什么建议吗?

最佳答案

不要对 ios::floatfield 使用 ios::fixed。这就是导致填充的原因。只需使用 setprecision

关于c++ - 使用 stringstream 精度格式化 float 但丢弃零填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15740658/

相关文章:

c++ - Qt:12.625 舍入 2 返回 12.62

c++ - NULL指针是不是和deallocating一样呢?

c++ - 从字符串流复制到 char * 数组返回作为函数参数

c++ - 我可以用逗号声明多个函数吗?

c++ - 追踪器 : error TRK0002: Failed to execute command

c++ - 什么时候应该抛出异常?

c++ - 相当于 %02d 与 std::stringstream?

c++ - istringstream、ostringstream 和 stringstream 有什么区别?/为什么不在每种情况下都使用 stringstream?

c++ - 如何读取动态大小的stringstream?

c++ - 从文件中读取 token (复杂)