#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");
}
记录一下