C ++:将double/float转换为字符串,保留科学计数法和精度 [英] C++: Converting a double/float to string, preserve scientific notation and precision
问题描述
我正在尝试将双精度/浮点数转换为字符串.其中一些数字包含科学符号"e",我想在转换后保留它.我搜索了google和stackoverflow,但没有找到与我的用例匹配的答案.
I'm trying to convert double/float numbers to string. Some of these numbers contain scientific notation "e", and I want to preserve it after the conversion. I searched through google and stackoverflow and didn't find a matching answer to my use case.
以下是一些示例和预期的输出:
Here are some examples and expected output:
input: 1.7976931348623157e+308
output: "1.7976931348623157e+308"
这是一个完整的 main.cc
文件,可以编译:
Here is a full main.cc
file that can be compiled:
#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 -----
--- Update 11:17AM -----
运行上面的独立代码后,不再有奇怪的字符,但是输出为长字符串格式的浮点数:
There is no more weird characters after running my standalone code above, but the output is a long string-formatted float:
179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.000000
不是预期的"1.7976931348623157e + 308".
Not the expected "1.7976931348623157e+308".
--------过时的----------------
-------- Outdated ----------------
但是输出是一个奇怪的字符串:
But the output is a weird string:
"179769313486231610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.000000ÍÍÍÍÍÍÍÍýýýý««««««««««««««««îþîþîþîþ"
推荐答案
两件事:
如果要使用科学记数法,则不需要的不是固定值.相反.
Fixed isn't what you want if you want scientific notation. It's the opposite.
我编译时
#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 ++编译器或标准库中存在错误.
which is right, which means there's a bug in your C++ compiler or standard library.
这篇关于C ++:将double/float转换为字符串,保留科学计数法和精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!