C ++:将double / float转换为string,保留科学记数法和精度

时间:2016-10-11 14:50:21

标签: c++

我正在尝试将double / float数字转换为字符串。其中一些数字包含科学记数法“e”,我希望在转换后保留它。我通过谷歌和stackoverflow搜索,并没有找到我的用例的匹配答案。

以下是一些示例和预期输出:

input: 1.7976931348623157e+308
output: "1.7976931348623157e+308"

这是一个可以编译的完整main.cc文件:

#include <iostream>
#include <sstream>
#include <string>

template <typename T>
std::string ToString(T value) {
  std::stringstream out;
  out << std::fixed;
  out << value;
  return out.str();
}

int main () {
    double mydouble = 1.7976931348623157e+308;
    std::cout << ToString(mydouble) << std::endl;
}

---更新11:17 AM -----

上面运行我的独立代码后没有更多奇怪的字符,但输出是一个长字符串格式的浮点数:

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

不是预期的“1.7976931348623157e + 308”。

--------过时----------------

但输出是一个奇怪的字符串:

"179769313486231610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000ÍÍÍÍÍÍÍÍýýýý««««««««««««««««îþîþîþîþ"

2 个答案:

答案 0 :(得分:1)

两件事:

如果您想要科学记数法,那么修复不是您想要的。恰恰相反。

编译时

#include <iostream>
#include <sstream>

template <typename T>
inline std::string ToString(T value) {
    std::stringstream out;
    out << std::fixed;  
    out << value;
    return out.str();
}
int main()  
{
    double mydouble = 1.7976931348623157e+308; 
    std::cout << ToString(mydouble) << std::endl; 
}

我得到了

179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

这是正确的,这意味着您的C ++编译器或标准库中存在错误。

答案 1 :(得分:1)

您的代码运行正常。如果输出中有垃圾值,则可能是其他地方存在堆栈损坏。

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

template <typename T>
inline std::string ToString(T value) {
  std::stringstream out;
  out << std::fixed;  
  out << value;
  return out.str();
}

int main() {
  double mydouble = 1.7976931348623157e+308; 
  std::cout << boost::lexical_cast<std::string>(mydouble) << '\n'; 
  std::cout << ToString(mydouble) << '\n';
}

输出:

  

1.7976931348623157e + 308   179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000

正如Marcus在之前的评论中指出的那样,你不想使用std :: fixed。