当然,C++ 11提供各类型的std::round来四舍五入,但是没有一个能直接支持保留小数点位数的四舍五入方案。
所以需要通过setprecision来实现:
1 #include <iomanip> 2 #include <iostream> 3 std::cout << std::fixed << setprecision(5) << 5.324356;
以上就是保留5位小数并四舍五入,如果把std::fixed去掉,那么就是保留5位有效位数并四舍五入。如果觉得标准输出流处理不方便,可以用封装stringstream类来实现字符串的转换的四舍五入函数:
1 #include <iomanip> 2 #include <sstream> 3 #include <iostream> 4 5 static std::string roundAny(double r,int precision){ 6 std::stringstream buffer; 7 buffer << std::fixed << setprecision(precision) << r; 8 return buffer.str(); 9 } 10 11 int main() 12 { 13 std::cout << roundAny(45.65658866,5) << std::endl; // C++11 14 std::cout << roundAny(21.6463,3) << std::endl; // C++11 15 return 0; 16 }