#include <iostream>
#include <iomanip>
#include <sstream>
std::string doubleToString(const double &val)
{
char* chCode;
chCode = new char[20];
sprintf(chCode, "%.2lf", val);
std::string str(chCode);
delete[]chCode;
return str;
}
int main()
{
double dNum = 123.45678901234;
//方法1:通过流的方式转成2位小数
std::stringstream ss;
ss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << dNum;
std::string str = ss.str();
std::cout << str << std::endl;
//方法2:通过sprintf(...)库函数来实现2位小数转换
std::string strCall = doubleToString(dNum);
std::cout << strCall << std::endl;
system("pause");
}
C++ 如何实现浮点数转字符串 并保留3位小数(已解决)
猜你喜欢
转载自blog.csdn.net/Vertira/article/details/134595057
今日推荐
周排行