How to Round a Double to an Int in C++

  1. Use the round() Function for Double to Int Rounding
  2. Use the lround() Function to Convert Double to the Nearest Integer
  3. Use the trunc() Function for Double to Int Rounding

This article will explain several methods of how to round a double to an integer in C++.

Use the round() Function for Double to Int Rounding

The round() function is defined in the <cmath> header. It can compute the nearest integer value of the argument that the user passes. Halfway cases are rounded away from zero, and the returned value is the same type as the argument. In the following example, we initialize an arbitrary vector of doubles and output the round() function for each element.

#include <cmath>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};

    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << round(item) << endl;
    }

    return EXIT_SUCCESS;
}

Output:

round(-3.5) = -4
round(-21.1) = -21
round(-1.99) = -2
round(0.129) = 0
round(2.5) = 3
round(3.111) = 3

Use the lround() Function to Convert Double to the Nearest Integer

Alternatively, we can use the lround() function, which behaves almost identically as the round() with one difference: it returns the value in a long integer format. Note that, for both functions, the return value can be unexpected, caused by different rounding errors, which are ubiquitous. Corresponding scenarios should be handled as specified in the documentation here.

#include <cmath>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};

    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << lround(item) << endl;
    }

    return EXIT_SUCCESS;
}

Use the trunc() Function for Double to Int Rounding

trunc() is another useful function from the <cmath> header, which computes the nearest integer not greater than the number passed as an argument. trunc() calculates the return value in the floating-point format as round(). Note that these two functions don’t take any effect from the current rounding mode. Error handling cases are described on the manual page.

#include <cmath>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};

    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << trunc(item) << endl;
    }

    return EXIT_SUCCESS;
}
round(-3.5) = -3
round(-21.1) = -21
round(-1.99) = -1
round(0.129) = 0
round(2.5) = 2
round(3.111) = 3

Related Article - C++ Double

  • How to Generate Random Double in C++
  • comments powered by Disqus