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.

Download  Run Code

 
To round a double down to 2 decimal places, you can use the std::ceil function as follows:

Download  Run Code

 
To round a double up to 2 decimal places, you can use the std::ceil function as follows:

Download  Run Code

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.

Download  Run Code

 
If you just need to write the formatted string to console, do as follows:

Download  Run Code

 
With C, you can achieve the same with the %.2f format string in the printf() function.

Download  Run Code

That’s all about restricting a floating-point value to two places after the decimal point in C++.