我需要将一个双精度浮点数存储为字符串。我知道可以使用printf
来显示它,但我只想将其存储在一个字符串变量中,以便稍后将其存储在映射中(作为值,而不是键)。
我需要将一个双精度浮点数存储为字符串。我知道可以使用printf
来显示它,但我只想将其存储在一个字符串变量中,以便稍后将其存储在映射中(作为值,而不是键)。
string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();
/* rest of the code */
#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
看一下 sprintf()
及其相关函数。
你可能想阅读我之前在SO上发布的帖子。(使用临时ostringstream对象的宏版本)
仅供参考:在我的代码中,我更喜欢使用snprintf()。使用本地堆栈上的char数组,效率并不低下。(好吧,也许如果你超出了数组大小并循环两次执行它...)
(我还通过vsnprintf()进行了包装。但这会导致一些类型检查的成本。如果需要代码,请留言...)
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);
C++17引入了: std::to_chars,std::to_chars_result - cppreference.com
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
更快。
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();
你可以使用这个函数将任何东西转换成任何东西:
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");