lrint() Function

The lrint() function rounds a floating-point value to the nearest integral value, following the current rounding mode, and then casts the result to a long integer. It is particularly useful when you need to convert a floating-point number into a long integer with proper rounding behavior.


Syntax of lrint()

</>
Copy
long int lrint(double x);

Parameters

ParameterDescription
xThe floating-point value to be rounded.

Note: The function rounds the value according to the current rounding mode, as set by fegetround(). If the rounded result exceeds the range representable by a long int, a domain or overflow error may occur depending on the implementation.


Examples for lrint()

Example 1: Basic Rounding of a Positive Floating-Point Number

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double value = 3.7;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}

Explanation:

  1. A positive floating-point number 3.7 is assigned to the variable value.
  2. The lrint() function rounds 3.7 to the nearest integer based on the current rounding mode.
  3. The rounded value is stored in the variable result and then printed.

Program Output:

Rounded result: 4

Example 2: Basic Rounding of a Negative Floating-Point Number

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double value = -2.3;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}

Explanation:

  1. A negative floating-point number -2.3 is stored in value.
  2. The lrint() function rounds the number to the nearest integral value considering the current rounding mode.
  3. The resulting long integer is stored in result and printed.

Program Output:

Rounded result: -2

Example 3: Rounding a Value Exactly at the Midpoint

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double value = 2.5;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}

Explanation:

  1. The midpoint value 2.5 is assigned to value.
  2. lrint() rounds 2.5 based on the current rounding mode.
  3. The resulting long integer is saved in result and printed.

Program Output:

Rounded result: 2

Example 4: Rounding a Large Floating-Point Number

Program

</>
Copy
#include <stdio.h>
#include <math.h>

int main() {
    double value = 12345678.9;
    long int result = lrint(value);
    printf("Rounded result: %ld\n", result);
    return 0;
}

Explanation:

  1. A large floating-point value 12345678.9 is stored in value.
  2. lrint() rounds the value to the nearest integral value, taking the current rounding mode into account.
  3. The result is cast to a long integer, stored in result, and then printed.

Program Output:

Rounded result: 12345679