gpt4 book ai didi

c++ - 使用 ostringstream 将 double 格式化为字符串

转载 作者:太空狗 更新时间:2023-10-29 20:27:55 27 4
gpt4 key购买 nike

我想将 double 转换为字符串,四舍五入到小数点后的 2 位小数。我希望 1.009 显示为“1.01”,1.0 显示为“1”。这是我试过的:

std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << std::noshowpoint << 1.0;

它输出“1.00”,即使我从未设置宽度甚至指定 std::noshowpoint。如何实现理想的表示?

最佳答案

最佳解决方案:

inline double twodec(double n) { return floor(n * 100 + 0.5) / 100; }

oss << twodec(1.0) << ' ' << twodec(1.009);

讨论

来自 http://www.cplusplus.com/reference/ios/fixed/ (斜体我的)

When floatfield is set to fixed, float values are written using fixed-point notation, which means the value is represented with exactly as many digits in the fraction part as specified by the precision field and with no exponent part.

所以,“固定”是行不通的。

也就是说,我能想到的做你想做的唯一方法是:

  • 首先将数字四舍五入到所需的精度(即 floor(n * 100 + 0.5)/100),然后使用默认表示(即不指定 fixed 或 scientific 或 precision -如果 fixedscientific 有效,首先使用 std::cout.unsetf(std::ios::floatfield) 清除它们。
  • 根据您希望在点前后看到的最大数字总数动态设置精度(这是精度指定的内容);为此,您可以算出小数点前的部分有多少位数字(也许使用对数基数 10)并加 2
  • 将结果流式传输到 ostringstream,然后删除尾随 0 和任何“.” (非常可怕)。

关于c++ - 使用 ostringstream 将 double 格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14851232/

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