简体   繁体   English

在C ++中将Double转换为字符串的问题

[英]Issue with Converting Double to String in C++

So I know setprecision(int n) should be used when printing a double value with precision n . 所以我知道在打印精度为n的双精度值时应使用setprecision(int n) However, I've run into a problem on a project that I'm working on that is akin to this code: 但是,我在一个正在处理的项目上遇到了一个类似于以下代码的问题:

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    double var = 1.0000001;
    cout << setprecision(10) << var << endl;
    string str = to_string(var);
    cout << str << endl;
    return 0;
}

Here is the output: 这是输出:

1.0000001
1.000000

In the project I'm working on, I need to save the double value as a string, and it will occasionally need more than six decimal places of precision. 在我正在处理的项目中,我需要将double值另存为字符串,并且偶尔需要超过六个小数位的精度。 Here, precision is clearly lost in the conversion. 在此,转换显然会损失精度。 Any pointers would be greatly appreciated. 任何指针将不胜感激。

Here's a reference for to_string . 这是to_string的参考。 Note that it produces "As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits". 请注意,它会产生“根据需要写入了许多数字以表示整数部分,后跟小数点字符和六个小数位”。

The rest of the question is a dupe of lots of SO ansers - see here , for example. 剩下的问题是很多SO分析器的重复-例如,请参见此处

我相信您正在寻找的是std :: fixed,如下所述: http : //www.cplusplus.com/reference/ios/fixed/

Using ostringstream will solve your problem. 使用ostringstream将解决您的问题。

#include <sstream>

double var = 1.0000001;
ostringstream os;
os << setprecision(10) << var;
string str = os.str();
cout << str << endl; // this should print 1.0000001

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM