C++ lround()

The lround() function in C++ rounds the integer value that is nearest to the argument, with halfway cases rounded away from zero. The value returned is of type long int.

The lround() function in C++ rounds the integer value that is nearest to the argument, with halfway cases rounded away from zero. The value returned is of type long int. It is similar to the round() function, but returns a long int whereas round returns the same data type as the input.


lround() prototype [As of C++ 11 standard]

long int lround(double x);
long int lround(float x);
long int lround(long double x);
long int lround(T x); // For integral type

The lround() function takes a single argument and returns a value of type long int. This function is defined in <cmath> header file.


lround() Parameters

The lround() function takes a single argument value to round.


lround() Return value

The lround() function returns the integral value that is nearest to x, with halfway cases rounded away from zero. The value returned is of type long int.


Example 1: How lround() works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{   
    long int result;
    double x = 11.16;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;

    x = 13.87;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = 50.5;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = -11.16;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;

    x = -13.87;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    x = -50.5;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;
    
    return 0;
}

When you run the program, the output will be:

lround(11.16) = 11
lround(13.87) = 14
lround(50.5) = 51
lround(-11.16) = -11
lround(-13.87) = -14
lround(-50.5) = -51

Example 2: lround() function for integral types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int x = 15;
    long int result;
    result = lround(x);
    cout << "lround(" << x << ") = " << result << endl;

    return 0;
}

When you run the program, the output will be:

lround(15) = 15

For integral values, applying the lround function returns the same value as the input. So it is not commonly used for integral values in practice.

Did you find this article helpful?