C++ 根据给定的精度,快速将双精度转换为字符串
我有一个使用C++ 根据给定的精度,快速将双精度转换为字符串,c++,sdl,ostringstream,C++,Sdl,Ostringstream,我有一个使用SDL的C++程序。在渲染期间,我需要绘制一些图形组件。有时我需要将double变量(四舍五入到一个小数点)转换为std::string 为此,我目前正在使用一个ostringstream对象,它工作正常 std::ostringstream ss; ss << std::fixed << std::setprecision(1) << x; std::ostringstream ss; ss不能使用std::to_string指定精度,因为它直
SDL
的C++
程序。在渲染期间,我需要绘制一些图形组件。有时我需要将double
变量(四舍五入到一个小数点)转换为std::string
为此,我目前正在使用一个ostringstream
对象,它工作正常
std::ostringstream ss;
ss << std::fixed << std::setprecision(1) << x;
std::ostringstream ss;
ss不能使用std::to_string
指定精度,因为它直接等效于printf
,参数为%f
(如果使用双精度
)
如果您关心的是不在每次分配流,您可以执行以下操作:
#include <iostream>
#include <sstream>
#include <iomanip>
std::string convertToString(const double & x, const int & precision = 1)
{
static std::ostringstream ss;
ss.str(""); // don't forget to empty the stream
ss << std::fixed << std::setprecision(precision) << x;
return ss.str();
}
int main() {
double x = 2.50000;
std::cout << convertToString(x, 5) << std::endl;
std::cout << convertToString(x, 1) << std::endl;
std::cout << convertToString(x, 3) << std::endl;
return 0;
}
另一种不使用ostringstream的解决方案
():
#包括
#包括
#包括
std::string my_to_string(const double&value){
const int length=std::snprintf(nullptr,0,“%.1f”,值);
std::unique_ptr buf(新字符[长度+1]);
std::snprintf(buf.get(),长度+1,“%.1f”,值);
返回std::string(buf.get());
}
int main(int argc,char*argv[])
{
std::cout考虑性能:ostringstream
将使用一个调用一些开销的locale
,否则,如果在渲染调用期间重复使用单个ostringstream
(内部缓冲区的单次分配/增长)然后应该没有比sprintf更多的开销,但它不起作用。你应该详细说明一下。万一你真的是说“它不起作用”,你确实用C++11编译器编译了,或者你的编译器设置为(至少)C++11标准,是吗?我确实用C++11编译器编译。没有做任何更改。我仍然将变量设置为2.500000000(例如)。@Q3SanD:嗯,std::setprecision
确实解决了这个问题。删除了我的答案,因为它发现错误的树。它仍然在使用ostringstream
(我想没有选择)但它比我的解决方案干净得多。我不会把它标记为答案,但我会投票表决。谢谢。@q3我添加了另一个没有ostringstream
的解决方案,但我不确定它是否更有效,你应该运行一个测试台。
#include <iostream>
#include <sstream>
#include <iomanip>
class DoubleToString
{
public:
DoubleToString(const unsigned int & precision = 1)
{
_ss << std::fixed;
_ss << std::setprecision(precision);
}
std::string operator() (const double & x)
{
_ss.str("");
_ss << x;
return _ss.str();
}
private:
std::ostringstream _ss;
};
int main() {
double x = 2.50000;
DoubleToString converter;
std::cout << converter(x) << std::endl;
return 0;
}
#include <iostream>
#include <string>
#include <memory>
std::string my_to_string(const double & value) {
const int length = std::snprintf(nullptr, 0, "%.1f", value);
std::unique_ptr<char[]> buf(new char[length + 1]);
std::snprintf(buf.get(), length + 1, "%.1f", value);
return std::string(buf.get());
}
int main(int argc, char * argv[])
{
std::cout << my_to_string(argc) << std::endl;
std::cout << my_to_string(2.5156) << std::endl;
}