Updated: April 19, 2023 |
Round a number to the closest integer
#include <math.h> double round( double x ); float roundf( float x ); long double roundl( long double x );
Your system requirements will determine how you should work with these libraries:
The round(), roundf(), and roundl() functions return x rounded to the nearest integer n, rounding halfway cases away from zero, regardless of the current rounding direction (i.e., returning the value with larger magnitude if |n − x| == 1/2).
To check for error situations, use feclearexcept() and fetestexcept(). For example:
The rounded value.
If x is: | rint() returns: | Errors: |
---|---|---|
±Inf | x | — |
NaN | x | — |
These functions raise FE_INEXACT if the FPU reports that the result can't be exactly represented as a floating-point number.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <fenv.h> int main (void) { int except_flags; double num1, result1; for (num1 = 3.0; num1 <= 4.0; num1 += 0.1) { feclearexcept(FE_ALL_EXCEPT); result1 = round (num1); except_flags = fetestexcept(FE_ALL_EXCEPT); if (except_flags) { /* An error occurred; handle it appropriately. */ } else { printf ("Rounding %f gives %f\n", num1, result1); } } return (EXIT_SUCCESS); }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | Yes |
Signal handler | Yes |
Thread | Yes |