在 C++ 中将浮点数转换为 std::string
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2125880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert float to std::string in C++
提问by adam_0
I have a float value that needs to be put into a std::string
. How do I convert from float to string?
我有一个需要放入std::string
. 如何从浮点数转换为字符串?
float val = 2.5;
std::string my_val = val; // error here
采纳答案by Georg Fritzsche
Unless you're worried about performance, use string 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 e.g. FastFormator simply the C-style functions.
有效的替代方法是例如FastFormat或简单的 C 样式函数。
回答by dmckee --- ex-moderator kitten
As of C++11, the standard C++ library provides the function std::to_string(arg)
with various supported types for arg
.
从 C++11 开始,标准 C++ 库std::to_string(arg)
为arg
.
回答by Rika
Important:
Read the note at the end.
重要提示:
阅读最后的注释。
Quick answer :
Use to_string()
. (available since c++11)
example :
快速回答:
使用to_string()
。(自 c++11 起可用)
示例:
#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
These are available as well :
自己运行: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);
Important Note:
As @Michael Kone?ny rightfully pointed out, using to_string()
is risky at best that is its very likely to cause unexpected results.
From http://en.cppreference.com/w/cpp/string/basic_string/to_string:
重要提示:
正如@Michael Kone?ny 正确指出的那样,使用to_string()
充其量是有风险的,因为它很可能会导致意想不到的结果。
从http://en.cppreference.com/w/cpp/string/basic_string/to_string:
With floating point types
std::to_string
may yield unexpected resultsas the number of significant digits in the returned string can be zero, see the example.
The return value may differ significantly from whatstd::cout
prints by default, see the example.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.C++17
providesstd::to_chars
as a higher-performance locale-independent alternative.
使用浮点类型
std::to_string
可能会产生意外结果,因为返回字符串中的有效位数可能为零,请参见示例。
返回值可能与std::cout
默认打印的显着不同,请参见示例。std::to_string
依赖当前语言环境进行格式化,因此std::to_string
来自多个线程的并发调用可能会导致调用的部分序列化。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
回答by dcp
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);
回答by Yochai Timmer
You can use std::to_stringin C++11
您可以在 C++11 中使用std::to_string
float val = 2.5;
std::string my_val = std::to_string(val);
回答by vitaut
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:
这种方法的优点是:
- It is locale-independent, preventing bugs when writing data into formats such as JSON that require '.' as a decimal point
- It provides shortest decimal representation with round trip guarantees
- It is potentially more efficient than other standard methods because it doesn't use the locale and doesn't require allocation
- 它与语言环境无关,可以防止在将数据写入需要 '.' 的 JSON 等格式时出现错误。作为小数点
- 它提供最短的十进制表示和往返保证
- 它可能比其他标准方法更有效,因为它不使用语言环境并且不需要分配
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, e.g.
不幸的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 P0645standards proposal gets approved.
C++20 可能会获得更方便的std::format
API,其好处std::to_chars
与P0645标准提案获得批准相同。
回答by David Gladfelter
If you're worried about performance, check out the Boost::lexical_castlibrary.
如果您担心性能,请查看Boost::lexical_cast库。
回答by tony gil
This tutorialgives 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);