[英]Convert float to std::string in C++
I have a float value that needs to be put into a std::string
.我有一个需要放入std::string
的浮点值。 How do I convert from float to string?如何从浮点数转换为字符串?
float val = 2.5;
std::string my_val = val; // error here
从 C++11 开始,标准 C++ 库为函数std::to_string(arg)
提供了各种支持的arg
类型。
Unless you're worried about performance, usestring streams :除非您担心性能,否则请使用字符串流:
#include <sstream>
//..
std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());
If you're okay with Boost, lexical_cast<> is a convenient alternative:如果你对 Boost 没问题, lexical_cast<>是一个方便的选择:
std::string s = boost::lexical_cast<std::string>(myFloat);
Efficient alternatives are eg FastFormat or simply the C-style functions.有效的替代方法是例如FastFormat或简单的 C 样式函数。
Important :重要:
Read the note at the end.阅读最后的注释。
Quick answer :快速回答 :
Use to_string()
.使用to_string()
。 (available since c++11) (自 c++11 起可用)
example :例子 :
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string pi = "pi is " + to_string(3.1415926);
cout<< "pi = "<< pi << endl;
return 0;
}
run it yourself : http://ideone.com/7ejfaU自己运行: http : //ideone.com/7ejfaU
These are available as well :这些也可用:
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);
Important Note:重要的提示:
As @Michael Konečný rightfully pointed out, using to_string()
is risky at best that is its very likely to cause unexpected results.正如@Michael Konečný 正确指出的那样,使用to_string()
充其量是有风险的,因为它很可能会导致意外结果。
From http://en.cppreference.com/w/cpp/string/basic_string/to_string :从http://en.cppreference.com/w/cpp/string/basic_string/to_string :
With floating point types
std::to_string
may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.对于浮点类型std::to_string
可能会产生意外的结果,因为返回的字符串中的有效位数可能为零,请参见示例。
The return value may differ significantly from whatstd::cout
prints by default, see the example.返回值可能与std::cout
默认打印的显着不同,请参见示例。std::to_string
relies on the current locale for formatting purposes, and therefore concurrent calls tostd::to_string
from multiple threads may result in partial serialization of calls.std::to_string
依赖当前语言环境进行格式化,因此从多个线程并发调用std::to_string
可能导致调用的部分序列化。C++17
providesstd::to_chars
as a higher-performance locale-independent alternative.C++17
提供std::to_chars
作为更高性能的语言环境独立替代方案。
The best way would be to use stringstream
as others such as @dcp demonstrated in his answer .:最好的方法是使用stringstream
作为其他人,例如 @dcp 在他的回答中展示的。:
This issue is demonstrated in the following example :以下示例演示了此问题:
run the example yourself : https://www.jdoodle.com/embed/v0/T4k自己运行示例: https : //www.jdoodle.com/embed/v0/T4k
#include <iostream>
#include <sstream>
#include <string>
template < typename Type > std::string to_str (const Type & t)
{
std::ostringstream os;
os << t;
return os.str ();
}
int main ()
{
// more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
double f = 23.43;
double f2 = 1e-9;
double f3 = 1e40;
double f4 = 1e-40;
double f5 = 123456789;
std::string f_str = std::to_string (f);
std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
std::string f_str5 = std::to_string (f5);
std::cout << "std::cout: " << f << '\n'
<< "to_string: " << f_str << '\n'
<< "ostringstream: " << to_str (f) << "\n\n"
<< "std::cout: " << f2 << '\n'
<< "to_string: " << f_str2 << '\n'
<< "ostringstream: " << to_str (f2) << "\n\n"
<< "std::cout: " << f3 << '\n'
<< "to_string: " << f_str3 << '\n'
<< "ostringstream: " << to_str (f3) << "\n\n"
<< "std::cout: " << f4 << '\n'
<< "to_string: " << f_str4 << '\n'
<< "ostringstream: " << to_str (f4) << "\n\n"
<< "std::cout: " << f5 << '\n'
<< "to_string: " << f_str5 << '\n'
<< "ostringstream: " << to_str (f5) << '\n';
return 0;
}
output :输出 :
std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43
std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09
std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40
std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40
std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08
You can define a template which will work not only just with doubles, but with other types as well.您可以定义一个模板,它不仅适用于双打,也适用于其他类型。
template <typename T> string tostr(const T& t) {
ostringstream os;
os<<t;
return os.str();
}
Then you can use it for other types.然后你可以将它用于其他类型。
double x = 14.4;
int y = 21;
string sx = tostr(x);
string sy = tostr(y);
Use std::to_chars
once your standard library provides it:一旦您的标准库提供std::to_chars
,请使用它:
std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
auto str = std::string(buf.data(), result.ptr - buf.data());
// use the string
} else {
// handle the error
}
The advantages of this method are:这种方法的优点是:
Unfortunately std::to_string
is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, eg不幸的是std::to_string
对浮点的效用有限,因为它使用固定表示,将小值四舍五入为零并为大值生成长字符串,例如
auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000
auto s2 = std::to_string(1e-40);
// s2 == 0.000000
C++20 might get a more convenient std::format
API with the same benefits as std::to_chars
if the P0645 standards proposal gets approved.如果P0645标准提案获得批准,C++20 可能会获得更方便的std::format
API,其优点与std::to_chars
to_chars相同。
You can use std::to_string in C++11您可以在 C++11 中使用std::to_string
float val = 2.5;
std::string my_val = std::to_string(val);
如果您担心性能,请查看Boost::lexical_cast库。
This tutorial gives a simple, yet elegant, solution, which i transcribe: 本教程提供了一个简单而优雅的解决方案,我将其转录为:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.