You could re-invent the wheel, as many other answers suggest. Alternately, you could use someone else's wheel -- I'd suggest Newlib's, which is BSD-licensed and intended for use on embedded systems. It properly handles negative numbers, NaNs, infinities, and cases which are not representable as integers (due to being too large), as well as doing so in an efficient manner that uses exponents and masking rather than generally-costlier floating-point operations. In addition, it's regularly tested, so you know it doesn't have glaring corner-case bugs in it.

The Newlib source can be a bit awkward to navigate, so here are the bits you want:

Float version: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/sf_round.c;hb=master

Double version: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/s_round.c;hb=master

Word-extraction macros defined here: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/fdlibm.h;hb=master

If you need other files from there, the parent directory is this one: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=tree;f=newlib/libm/common;hb=master

For the record, here's the code for the float version. As you can see, there's a bit of complexity required to deal with all the possible cases correctly.

float roundf(x)
{
  int signbit;
  __uint32_t w;
  /* Most significant word, least significant word. */
  int exponent_less_127;

  GET_FLOAT_WORD(w, x);

  /* Extract sign bit. */
  signbit = w & 0x80000000;

  /* Extract exponent field. */
  exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;

  if (exponent_less_127 < 23)
    {
      if (exponent_less_127 < 0)
        {
          w &= 0x80000000;
          if (exponent_less_127 == -1)
            /* Result is +1.0 or -1.0. */
            w |= ((__uint32_t)127 << 23);
        }
      else
        {
          unsigned int exponent_mask = 0x007fffff >> exponent_less_127;
          if ((w & exponent_mask) == 0)
            /* x has an integral value. */
            return x;

          w += 0x00400000 >> exponent_less_127;
          w &= ~exponent_mask;
        }
    }
  else
    {
      if (exponent_less_127 == 128)
        /* x is NaN or infinite. */
        return x + x;
      else
        return x;
    }
  SET_FLOAT_WORD(x, w);
  return x;
}
Answer from Brooks Moses on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › c language › round-function-in-c
round() Function in C - GeeksforGeeks
July 5, 2024 - C round() is a built-in library function that rounds a floating-point number to the nearest integer. If the fractional part of the number is 0.5 or greater, the argument is rounded away from zero.
🌐
W3Schools
w3schools.com › c › ref_math_round.php
C Math round() Function
C Examples C Real-Life Examples ... printf("%f", round(-5.9)); Try it Yourself » · The round() function rounds a number to the nearest integer....
Discussions

math - Concise way to implement round() in C? - Stack Overflow
The embedded C I'm using doesn't have a round() function it it's math lib, what would be a concise way to implement this in C? I was thinking of printing it to a string, looking for the decimal pl... More on stackoverflow.com
🌐 stackoverflow.com
Rounding in C
Have you considered simply trying the code out? More on reddit.com
🌐 r/C_Programming
37
0
May 8, 2024
rounding - How to round floating point numbers to the nearest integer in C? - Stack Overflow
The rint functions differ from the nearbyint functions (7.12.9.3) only in that the rint functions may raise the ‘‘inexact’’ floating-point exception if the result differs in value from the argument. C11dr §7.12.9.4 2 ... The round functions round their argument to the nearest integer ... More on stackoverflow.com
🌐 stackoverflow.com
How to round to the nearest integer?
You can safely cast the results of round or roundf to long. C also provides a function that does this for you, lround and lroundf. The round functions return the nearest integer in float format, it will not return something like 4.9999999, it will return a number that represents 5 exacts. Except... Floating point is weird, because of course it is. Floating point can't represent all integers exactly, and larger than positive or negative 224 for 32-bit floats and 253 for 64-bit doubles present problems. If your numbers are within a reasonable range then the above holds true. If your numbers are outside this range then unpredictable things may occur. More on reddit.com
🌐 r/C_Programming
16
16
January 13, 2024
🌐
Cppreference
cppreference.com › w › c › numeric › math › round.html
round, roundf, roundl, lround, lroundf, lroundl, llround, llroundf, llroundl - cppreference.com
May 23, 2024 - Common mathematical functions · [edit] 1-3) Computes the nearest integer value to arg (in floating-point format), rounding halfway cases away from zero, regardless of the current rounding mode. 5-7, 9-11) Computes the nearest integer value to arg (in integer format), rounding halfway cases ...
Top answer
1 of 10
23

You could re-invent the wheel, as many other answers suggest. Alternately, you could use someone else's wheel -- I'd suggest Newlib's, which is BSD-licensed and intended for use on embedded systems. It properly handles negative numbers, NaNs, infinities, and cases which are not representable as integers (due to being too large), as well as doing so in an efficient manner that uses exponents and masking rather than generally-costlier floating-point operations. In addition, it's regularly tested, so you know it doesn't have glaring corner-case bugs in it.

The Newlib source can be a bit awkward to navigate, so here are the bits you want:

Float version: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/sf_round.c;hb=master

Double version: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/s_round.c;hb=master

Word-extraction macros defined here: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=blob;f=newlib/libm/common/fdlibm.h;hb=master

If you need other files from there, the parent directory is this one: https://sourceware.org/git/gitweb.cgi?p=newlib-cygwin.git;a=tree;f=newlib/libm/common;hb=master

For the record, here's the code for the float version. As you can see, there's a bit of complexity required to deal with all the possible cases correctly.

float roundf(x)
{
  int signbit;
  __uint32_t w;
  /* Most significant word, least significant word. */
  int exponent_less_127;

  GET_FLOAT_WORD(w, x);

  /* Extract sign bit. */
  signbit = w & 0x80000000;

  /* Extract exponent field. */
  exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;

  if (exponent_less_127 < 23)
    {
      if (exponent_less_127 < 0)
        {
          w &= 0x80000000;
          if (exponent_less_127 == -1)
            /* Result is +1.0 or -1.0. */
            w |= ((__uint32_t)127 << 23);
        }
      else
        {
          unsigned int exponent_mask = 0x007fffff >> exponent_less_127;
          if ((w & exponent_mask) == 0)
            /* x has an integral value. */
            return x;

          w += 0x00400000 >> exponent_less_127;
          w &= ~exponent_mask;
        }
    }
  else
    {
      if (exponent_less_127 == 128)
        /* x is NaN or infinite. */
        return x + x;
      else
        return x;
    }
  SET_FLOAT_WORD(x, w);
  return x;
}
2 of 10
22
int round(double x)
{
    if (x < 0.0)
        return (int)(x - 0.5);
    else
        return (int)(x + 0.5);
}
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › round-roundf-roundl
round, roundf, roundl | Microsoft Learn
July 9, 2025 - Because C++ allows overloading, you can call overloads of round that take and return float and long double values. In a C program, unless you're using the <tgmath.h> macro to call this function, round always takes and returns a double.
Find elsewhere
🌐
Reddit
reddit.com › r/c_programming › rounding in c
r/C_Programming on Reddit: Rounding in C
May 8, 2024 -

I have a question when it comes to rounding in C. Does it round up or down at .5? If it does round up, then does that mean that the smallest value of k in the code below can only be 1?

 int main()
{
    int k = 13;
    int i;
    for (i = 0; i < 8; i++) {
        printf("%d", (k%2));
        k >>= 1;
    }
    printf("%n");
}

🌐
Scaler
scaler.com › home › topics › c round() function
C round() Function - Scaler Topics
March 27, 2024 - The C round() function is one of ... The round() function in C returns the nearest integer value (rounded value) of the given float, integer, or double number based on the decimal part of the number....
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re199.html
round C99 - C in a Nutshell [Book]
December 16, 2005 - If the argument is exactly halfway between two integers, round() rounds it away from 0. The return value is the rounded integer value. See the example for nearbyint() in this chapter.
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_round.htm
C library - round() function
The C library round() function can be used to calculate the floating-point into the nearest integer. This function is a part of C99 standard and defined under the header math.h.
Top answer
1 of 11
17

To round a float in C, there are 3 <math.h> functions to meet the need. Recommend rintf().

float nearbyintf(float x);

The nearbyint functions round their argument to an integer value in floating-point format, using the current rounding direction and without raising the ‘‘inexact’’ floating point exception. C11dr §7.12.9.3 2

or

float rintf(float x);

The rint functions differ from the nearbyint functions (7.12.9.3) only in that the rint functions may raise the ‘‘inexact’’ floating-point exception if the result differs in value from the argument. C11dr §7.12.9.4 2

or

float roundf(float x);

The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction. C11dr §7.12.9.6 2


Example

#include <fenv.h>
#include <math.h>
#include <stdio.h>

void rtest(const char *fname, double (*f)(double x), double x) {
  printf("Clear inexact flag       :%s\n", feclearexcept(FE_INEXACT) ? "Fail" : "Success");
  printf("Set round to nearest mode:%s\n", fesetround(FE_TONEAREST)  ? "Fail" : "Success");

  double y = (*f)(x);
  printf("%s(%f) -->  %f\n", fname,x,y);

  printf("Inexact flag             :%s\n", fetestexcept(FE_INEXACT) ? "Inexact" : "Exact");
  puts("");
}

int main(void) {
  double x = 8.5;
  rtest("nearbyint", nearbyint, x);
  rtest("rint", rint, x);
  rtest("round", round, x);
  return 0;
}

Output

Clear inexact flag       :Success
Set round to nearest mode:Success
nearbyint(8.500000) -->  8.000000
Inexact flag             :Exact

Clear inexact flag       :Success
Set round to nearest mode:Success
rint(8.500000) -->  8.000000
Inexact flag             :Inexact

Clear inexact flag       :Success
Set round to nearest mode:Success
round(8.500000) -->  9.000000
Inexact flag             :Exact

What is weak about OP's code?

(int)(num < 0 ? (num - 0.5) : (num + 0.5))
  1. Should num have a value not near the int range, the cast (int) results in undefined behavior.

  2. When num +/- 0.5 results in an inexact answer. This is unlikely here as 0.5 is a double causing the addition to occur at a higher precision than float. When num and 0.5 have the same precision, adding 0.5 to a number may result in numerical rounded answer. (This is not the whole number rounding of OP's post.) Example: the number just less than 0.5 should round to 0 per OP's goal, yet num + 0.5 results in an exact answer between 1.0 and the smallest double just less than 1.0. Since the exact answer is not representable, that sum rounds, typically to 1.0 leading to an incorrect answer. A similar situation occurs with large numbers.


OP's dilemma about "The above line always prints the value as 4 even when float num =4.9." is not explainable as stated. Additional code/information is needed. I suspect OP may have used int num = 4.9;.


// avoid all library calls
// Relies on UINTMAX_MAX >= FLT_MAX_CONTINUOUS_INTEGER - 1
float my_roundf(float x) {
  // Test for large values of x 
  // All of the x values are whole numbers and need no rounding
  #define FLT_MAX_CONTINUOUS_INTEGER  (FLT_RADIX/FLT_EPSILON)
  if (x >= FLT_MAX_CONTINUOUS_INTEGER) return x;
  if (x <= -FLT_MAX_CONTINUOUS_INTEGER) return x;

  // Positive numbers
  // Important: _no_ precision lost in the subtraction
  // This is the key improvement over OP's method
  if (x > 0) {
    float floor_x = (float)(uintmax_t) x;
    if (x - floor_x >= 0.5) floor_x += 1.0f;
    return floor_x;
  }

  if (x < 0) return -my_roundf(-x);
  return x; //  x is 0.0, -0.0 or NaN
}

Tested little - will do so later when I have time.

2 of 11
16

4.9 + 0.5 is 5.4, which cannot possibly round to 4 unless your compiler is seriously broken.

I just confirmed that the Googled code gives the correct answer for 4.9.

marcelo@macbookpro-1:~$ cat round.c 
#include <stdio.h>

int main() {
    float num = 4.9;
    int n = (int)(num < 0 ? (num - 0.5) : (num + 0.5));
    printf("%d\n", n);
}
marcelo@macbookpro-1:~$ make round && ./round
cc     round.c   -o round
5
marcelo@macbookpro-1:~$
🌐
Cppreference
en.cppreference.com › w › cpp › numeric › math › round.html
std::round, std::roundf, std::roundl, std::lround, std::lroundf, std::lroundl, std::llround, std::llroundf - cppreference.com
March 14, 2025 - The additional overloads are not required to be provided exactly as (A-C). They only need to be sufficient to ensure that for their argument num of integer type: std::round(num) has the same effect as std::round(static_cast<double>(num)).
🌐
CodeToFun
codetofun.com › c › math-round
C round() Function | CodeToFun
November 16, 2024 - The round() function is a standard library function in C that is used to round a floating-point value to the nearest integer, using the current rounding mode.
🌐
Codecademy
codecademy.com › docs › c++ › math functions › round()
C++ (C Plus Plus) | Math Functions | round() | Codecademy
December 21, 2022 - The round() function returns the integer that is closest to the argument, with halfway cases rounded away from the ending zero.
🌐
CodeProject
codeproject.com › articles › C-Round-Function
C Round Function - CodeProject
It's really weird that the C math library (math.h) doesn't support the round function. This post shows how to create one in C. Pretty simple, but can save you l