C++ lrint()

The lrint() function in C++ rounds the argument to an integral value using the current rounding mode.

The lrint() function in C++ rounds the argument to an integral value using the current rounding mode. The current rounding mode is determined by the function fesetround(). It is similar to rint(), but returns long int.


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

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

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


lrint() Parameters

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


lrint() Return value

The lrint() function rounds the argument x to an integral value, using the rounding direction specified by fegetround() and returns the value in long int.

By default, the rounding direction is set to 'to-nearest'. The rounding direction can be set to other values using fesetround() function.


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

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;

int main()
{
    // by default, rounding direction is to-nearest i.e. fesetround(FE_TONEAREST)
    double x = 11.87;
    long int result;
    result = lrint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;
    
    // mid-way values are rounded off to higher integer
    x = 11.5;
    result = lrint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;

    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 11.87;
    result = lrint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;
    
    // setting rounding direction to UPWARD
    fesetround(FE_UPWARD);
    x = 33.32;
    result = lrint(x);
    cout << "Rounding upward (" << x << ") = " << result << endl;
    
    return 0;
}

When you run the program, the output will be:

Rounding to-nearest (11.87) = 12
Rounding to-nearest (11.5) = 12
Rounding downward (11.8699) = 11
Rounding upward (33.3201) = 34

Example 2: lrint() function for integral types

#include <iostream>
#include <cmath>
#include <cfenv>
using namespace std;

int main()
{
    int x = 15;
    long int result;
    
    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    result = lrint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;
    return 0;
}

When you run the program, the output will be:

Rounding downward (15) = 15

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