如何在C++中将double转换为字符串?

202

我需要将一个双精度浮点数存储为字符串。我知道可以使用printf来显示它,但我只想将其存储在一个字符串变量中,以便稍后将其存储在映射中(作为,而不是)。


2
一个问题来回答你的问题:为什么要将双精度值存储在字符串中再存储到映射中?你打算使用字符串化的双精度作为键吗?如果不是,为什么不保留双精度值呢? - Matt McClellan
1
有趣的观点。在地图键中使用double可能存在一些风险,因为浮点值上的精确比较总是如此。在字符串表示法上进行索引避免了这个问题。 - Fred Larson
2
为什么要进行转换呢?将其存储在映射表中作为双精度浮点数,并避免进行转换。 - EvilTeach
3
听起来仍然需要使用对象。使用一个联合体会比较合适。每个对象可以插入不同的值,并自我验证。 - EvilTeach
2
我只有一个文件中的一堆名称/值对,不需要使用对象。 - Bill the Lizard
显示剩余4条评论
18个回答

4
嘿,我刚刚写了这个(与此问题无关):
string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

2
请注意,字符串只是双精度浮点数的表示形式,将其转换回双精度浮点数可能不会得到相同的值。同时请注意,默认的字符串转换可能会将转换结果截断到一定的精度。
按照标准C++的方式,您可以通过以下方法控制精度:
#include <sstream>
#include <math.h>
#include <iostream>
#include <iomanip>

int main()
{
    std::ostringstream sout;
    sout << M_PI << '\n';
    sout << std::setprecision(99) << M_PI << '\n';
    sout << std::setprecision(3) << M_PI << '\n';
    sout << std::fixed; //now the setprecision() value will look at the decimal part only.
    sout << std::setprecision(3) << M_PI << '\n';
    std::cout << sout.str();
}

这将会给你输出结果。

3.14159                                                                                                                                                                            
3.141592653589793115997963468544185161590576171875                                                                                                                                 
3.14                                                                                                                                                                               
3.142  

2

看一下 sprintf() 及其相关函数。


3
我提到printf是因为通过谷歌搜索发现有许多文章称要将double转换为字符串就要使用printf。这些文章假定你所要做的唯一事情就是打印,而在我的情况下这是错误的。 - Bill the Lizard
为什么你投-1?我认为sprintf很好。@BilltheLizard,sprint将某些内容打印到char *而不是屏幕上。有人回答了C方法,仍然得到了很多票。 - worldterminator

2

1
使用 to_string() 函数。
例如:
#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

自己运行它:http://ideone.com/7ejfaU
这些也可用:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

0

C++17引入了: std::to_chars,std::to_chars_result - cppreference.com


(Note: The translated text is in Simplified Chinese)
std::to_chars_result to_chars( char* first, char* last, float       value,
                               std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, double      value,
                               std::chars_format fmt, int precision );
std::to_chars_result to_chars( char* first, char* last, long double value,
                               std::chars_format fmt, int precision );

提供快速低级方式将浮点数转换为字符串,并具有一定的格式控制。由于不进行任何分配,因此应该很快,只有特定场景的自定义实现才应更快。

C++20引入了高级易于使用的格式化字符串(等同于fmt库):

std::format - cppreference.com

std::format

template< class... Args >
std::string format( /*format_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::wstring format( /*wformat_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::string format( const std::locale& loc,
                    /*format_string<Args...>*/ fmt, Args&&... args );

template< class... Args >
std::wstring format( const std::locale& loc,
                     /*wformat_string<Args...>*/ fmt, Args&&... args );

这非常好用和方便。应该比sprintf更快。


0
你可以尝试更紧凑的风格:
std::string number_in_string;

double number_in_double;

std::ostringstream output;

number_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<

std::endl)))->str(); 

0

你可以使用这个函数将任何东西转换成任何东西:

template<class T = std::string, class U>
T to(U a) {
    std::stringstream ss;
    T ret;
    ss << a;
    ss >> ret;
    return ret;
};

用法:

std::string str = to(2.5);
double d = to<double>("2.5");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接