Restrict a float to two places after the decimal point in C++
This post will discuss how to restrict a floating-point value to two places after the decimal point in C++.
1. Using round() function
There are several options to restrict a floating-point to two decimal places, depending upon if you may want to round the number to nearest, round down, or round up. For example, the following code rounds a floating-point to two decimal places.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = round(f * 100) / 100; std::cout << value << std::endl; // 10.52 return 0; } |
To round a double down to 2 decimal places, you can use the std::ceil function as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = floor(f * 100) / 100; std::cout << value << std::endl; // 10.51 return 0; } |
To round a double up to 2 decimal places, you can use the std::ceil function as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; float value = ceil(f * 100) / 100; std::cout << value << std::endl; // 10.52 return 0; } |
2. Using std::ios_base::precision
The std::ios_base::precision function is used to set the decimal precision for a floating-point value for the stream. You could use std::ostringstream with the precision specifier as for std::cout.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <sstream> std::string format(float f, int digits) { std::ostringstream ss; ss.precision(digits); ss << f; return ss.str(); } int main() { float f = 10.517986; int digits = 4; std::string value = format(f, digits); std::cout << value << std::endl; // 10.52 return 0; } |
If you just need to write the formatted string to console, do as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <cmath> int main() { float d = 10.517986; std::cout.precision(4); std::cout << d << std::endl; // 10.52 return 0; } |
With C, you can achieve the same with the %.2f format string in the printf() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <cmath> int main() { float f = 10.517986; printf("%.2f", f); // 10.52 return 0; } |
That’s all about restricting a floating-point value to two places after the decimal point in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)