【问题标题】:How to convert double to string with precision for total number of digits(both left and right side of the decimal)?如何将双精度转换为字符串的总位数(小数点的左侧和右侧)?
【发布时间】:2021-03-28 01:17:06
【问题描述】:

我正在寻找一种在 c++ 中将双精度转换为字符串的方法,这样无论小数点前后有多少位,也不管零位如何,总位数保持为 10。便于理解的示例:

0.00000000000000000000 =预期结果> 0.0000000000

12345.00000000000000000 =预期结果> 12345.00000

-15.123456789012 =预期结果> -15.12345678

我找不到任何相关的答案。对于 snprintf、std::setprecision with ostringstream、to_string、Boost 的 lexical_cast 等方法,上述一些情况会失败。

代码示例:

double num = 12345.0000000000001;

std::ostringstream streamObj2;

streamObj2 << std::fixed <<  std::setprecision(10) << num;

std::string strObj2 = streamObj2.str();

std::cout  << strObj2 << '\n';

输出 = 12345.0000000000,这不是我所期望的。删除 std::fixed 输出为 12345

我需要的 = 12345.00000

请帮帮我,谢谢。

【问题讨论】:

  • 没有什么叫 C/C++。
  • 这不是std::setprecision 所做的吗?哪种情况失败?请在问题中包含您的代码
  • std::setprecision 仅根据我搜索的内容设置小数点后数字的精度
  • @Rogenwiczar 不,那不是它的作用。请在问题中包含您的代码的minimal reproducible example
  • @Maliafo 并没有说 std::setprecision 单独是解决方案。而是试图让 OP 发布他们的代码,以便我们可以看到实际缺少的内容

标签: c++ c++11


【解决方案1】:

感谢 cmets,因此我找到了答案。使用 std::showpoint 代替 std::fixed 有助于满足要求。

双数 = 12345.0000000000001;

std::ostringstream streamObj2;

streamObj2 std::showpoint

std::string strObj2 = streamObj2.str();

std::cout

输出:12345.00000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多