C++11保留小数点的的四舍五入方案
通常有两种常用的方法:
通过Setprecision()实现
#include <iomanip>
#include <iostream>
std::cout << std::fixed << setprecision(5) << 1.234567;
上面程序示例即可达到保留5位小数并四舍五入,但如果把std::fixed去掉,就是保留5位小数并且四舍五入。
通过stringstream实现
#include <iomanip>
#include <sstream>
#include <iostream>
static std::string roundAny(double r,int precision){
std::stringstream buffer;
buffer << std::fixed << setprecision(precision) << r;
return buffer.str();
}
int main()
{
std::cout << roundAny(88.88866,5) << std::endl;
return 0;
}