【问题标题】:C++ : Removing scientific notation from number while converting to stringC ++:在转换为字符串时从数字中删除科学记数法
【发布时间】:2017-08-22 12:51:45
【问题描述】:

我看到所有示例都说要使用 fixedprecision 等,但所有这些都是人们想要打印值的时候。

我要做的是将我的双精度值从数字转换为字符串,我不需要科学记数法。

我的号码示例:6.61914e+6

那么,当我的大部分号码都不是很长时,如何以简单的方式完成。

【问题讨论】:

标签: c++


【解决方案1】:

引用std::to_string(double)描述:

根据需要写入尽可能多的数字来表示整数部分, 后跟小数点字符和六位小数。

std::string s = std::to_string(6.61914e+6);

如果小数点后这个位数不够,可以使用std::ostringstream

std::ostringstream str;
str << std::fixed << std::setprecision(digits) << 6.61914e+6;
std::string s = str.str();

如果您想删除尾随零(根据Robinson 的评论和对此question 的回答):

s.erase(s.find_last_not_of('0') + 1, std::string::npos);  

【讨论】:

  • 6619136.000000 但是我们是否必须再次进行字符串操作以删除零,因为它们最初不存在并且不需要。
  • 你可以用 s.erase(s.find_last_not_of('0') + 1,std::string::npos );不过你是对的,iomanip 中应该有一些东西告诉 stringstream 不要这样做。任何事物的 IDK。
【解决方案2】:

您可以使用std::to_string 函数来完成任务:

double x = 6.61914e+6;
auto mystr = std::to_string(x);

【讨论】:

  • 6619136.000000 但是如何删除尾随零。原始数字甚至没有那些零。
  • 6.61913E+6 的值是 6619130(至少在有限浮点精度的范围内)。尾随零是必需的,否则字符串中的值表示不正确。如果您想删除'.' 之后的零,很容易解析和删除它们。
  • @Peter 是的,但是如果我们在大多数情况下转换为字符串,我们可能不需要小数点后的零。这样就增加了一个删除小数点后零的步骤。
【解决方案3】:

您可以将 std::stringstream 与您已经知道的一起使用 - std::fixedstd::setprecision

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

int main()
{
    std::stringstream ss;
    ss << std::fixed << std::setprecision(0) << 6.61914e+6;
    std::cout << ss.str() << "\n";
}

输出:

6619140

Coliru

正如正确评论的那样,这不好,因为您需要知道精度

我能看到的唯一灵活的方式是:

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

int main()
{
    std::stringstream ss;
    ss << std::fixed << 6.61914e+6;
    std::string s = ss.str();
    s.erase(s.find_last_not_of('0') + 1, std::string::npos );
    std::cout << s << "\n";    
}

【讨论】:

  • 这仅适用于整数。如果精度为 0,您将丢失任何其他内容。
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多