【问题标题】:Convert large double to scientific notation for use as string? [duplicate]将大双精度数转换为科学记数法以用作字符串? [复制]
【发布时间】:2017-08-03 06:35:20
【问题描述】:

这个问题很明显绝不是标记问题的“完全重复”,并且该帖子没有解决我的目标。

如果我有:

double yuge = 1e16;

我尝试将它添加到这样的字符串中:

std::string boogers = std::to_string (yuge) + ".csv";

我得到一个文件名 100000000000000000.csv。

我想要一个不错的紧凑版本,例如 1e16.csv。

如您所见,我想将其用作文件名,因此输出方法没有帮助。哈!谢谢。

【问题讨论】:

  • 自从有了operator+(double, char*)?显示您用来完成此操作的实际代码,而不是废话。
  • 从平静下来的时候先生。你显然知道我的意思。固定。
  • 不,我不明白你的意思。完全由你来解释你的问题。这不是猜谜游戏。
  • @JobGuidos 您成为会员已经一年多了。到目前为止,您应该知道how to ask good questions 以及如何创建Minimal, Complete, and Verifiable Example
  • 我建议你自己而不是别人。会更容易获得帮助。

标签: c++ string double filenames scientific-notation


【解决方案1】:

您可以使用std::stringstream 代替+ 运算符来构造字符串。

#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>

int main()
{
  double youge = 1e16;
  std::stringstream ss;
  ss<<youge<<".csv";
  std::string filename = ss.str(); // filename = 1e+16.csv
  filename.erase(std::remove(filename.begin(), filename.end(), '+'), filename.end());// removing the '+' sign
  std::cout<<filename; // 1e16.csv
}

【讨论】:

  • 这是一个非常令人惊讶的解决方案。我从来没有想过要检查流流是否任意将数字存储为科学记数法。谢谢你。完美的答案。你看不到我的投票,但我看到了。
  • 显然它适用于双打 >=1e6(link) 在其他情况下,也许ss&lt;&lt;std::scientific&lt;&lt;youge 会更好。
  • 使用该建议会产生很多零,但this 似乎可以工作,只要我不将它用于会产生 193e5 的 1.903e5 之类的东西。幸运的是,我现在的数字恰好大于 1e6,而且很简单。如果有人有另一个干净的解决方案,请发布另一个答案。也许在数学或科学图书馆里有什么?谢谢。
猜你喜欢
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2011-06-02
  • 2020-07-17
相关资源
最近更新 更多