This post will discuss how to round floating-point value to the nearest int in C++.

1. Using std::round

Starting with C++11, the std::round function is the most elegant way to round a floating-point value to the nearest int. If your compiler supports it, you can use it as follows:

Download  Run Code

 
The std::round function is defined in the <cmath> header (in C++11). You may also use the std::lround and std::llround function to round the specified floating-point value to the nearest integer value, returned as long integer and long long integer, respectively.

2. Using std::floor

There’s no round function in the C++98 standard library. However, you can easily write your rounding function with std::floor function. The following code implements round-half-up logic:

Download  Run Code

3. Using boost

Another option is to use the rounding functions offered by the boost library. There are several functions in the header <boost/math/special_functions/round.hpp> – that return the closest integer to the specified argument.

 
T round(const T& v);
int iround(const T& v);
long lround(const T& v);
long long llround(const T& v);

 
Note that halfway cases are rounded away from zero, as shown below:

Download Code

4. Using std::trunc

If you need to truncate the value to the nearest integer, instead of rounding it, consider using the std::trunc function. This is demonstrated below:

Download  Run Code

 
Another possibility is using static cast which provides a safe way to convert from one type to another. You can do something like:

Download  Run Code

That’s all about rounding a floating-point value to the nearest int in C++.