How to round floating point numbers to the nearest integer in C?
Solution 1
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:~$
Solution 2
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 thenearbyint
functions (7.12.9.3) only in that therint
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))
Should
num
have a value not near theint
range, the cast(int)
results in undefined behavior.When
num +/- 0.5
results in an inexact answer. This is unlikely here as0.5
is adouble
causing the addition to occur at a higher precision thanfloat
. Whennum
and0.5
have the same precision, adding0.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, yetnum + 0.5
results in an exact answer between 1.0 and the smallestdouble
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.
Solution 3
I'm not sure that's such a good idea. That code depends on casts, and I'm fairly sure that the exact truncation is undefined.
float result = (num - floor(num) > 0.5) ? ceil(num) : floor(num);
I'd say that this is a much better way (which is basically what Shiroko posted) since it doesn't depend on any casts.
Solution 4
A general solution is to use rint() and set the FLT_ROUNDS rounding mode as appropriate.
Solution 5
the googled code works correctly. The idea behind it is that you round down when the decimal is less than .5 and round up otherwise. (int)
casts the float into a int type which just drops the decimal. If you add .5 to a positive num, you get drop to the next int. If you subtract .5 from a negative it does the same thing.
webgenius
Updated on October 10, 2020Comments
-
webgenius over 3 years
Is there any way to round numbers in C?
I do not want to use ceil and floor. Is there any other alternative?
I came across this code snippet when I Googled for the answer:
(int)(num < 0 ? (num - 0.5) : (num + 0.5))
The above line always prints the value as 4 even when float num =4.9.
-
Admin about 14 yearsThere are many different types of rounding - which one(s) do you want to use? Please post examples of the desired behaviour.
-
IVlad about 14 yearsI think the problem is somewhere else, that should definitely print 5 for an input of 4.9.
-
Arkku about 14 yearsYes, the conversion of a floating point type to an integer type that can represent a number of the required signedness and magnitude should work simply by truncating the decimals; this code does the ±0.5 to cause this truncation to round the original value away from zero.
-
kennytm about 14 yearsWhat's wrong with
ceil
andfloor
? Also, see stackoverflow.com/questions/485525/round-for-float-in-c. -
Earlz about 14 years
-
AnT stands with Russia almost 14 yearsThe above line does not print anything. There is nothing in that line that can possibly do any printing. Show us how you print things. The problem is likely there.
-
Ciro Santilli OurBigBook.com about 7 yearsSubset: specific for integer division: stackoverflow.com/questions/2422712/… | C++ stackoverflow.com/questions/485525/round-for-float-in-c
-
-
Alex S about 14 yearsThis has no effect other than to possibly raise a warning when you assign this expression to an int. Also, the
(int)
cast is redundant, sincenum < 0
already has typeint
. -
webgenius about 14 yearsHmmm....You're right....The statement can be further simplified to: int n = (num < 0) ? (num - 0.5) : (num + 0.5); I've checked this and it works flawless. Can you please explain how the (num<0) comparison works? I inserted a breakpoint in my IDE and saw that the condition check (num<0) always points to FALSE, which should execute (num + 0.5) always
-
Ali Lown about 14 yearsWhat do you mean this is can't possibly work. This is the same as the answer that has 4 up votes.
-
Steve Jessop about 14 yearsIf the questioner genuinely doesn't want to use ceil and floor, but genuinely is happy to use the built-in conversion to int, then the question can be filed under "quirky interview-style questions which involve an unnatural restriction to illustrate some point fully understood only by the interviewer". Unfortunately that doesn't fit in a tag.
-
Arkku about 14 yearsNot sure what you are asking, but an expression
a ? b : c
evaluates tob
ifa
is true and toc
otherwise. In this case the idea is to move the value ofnum
away from zero by0.5
before converting it to int by truncating the decimals. This way the truncation will round to the nearest int (e.g. 0.5 + 0.5 = 1.0 and 0.99 + 0.5 = 1.49 both truncate to 1). -
webgenius about 14 yearsSteve, you are right. This is an question often asked in interviews.
-
Dan Story about 14 yearsThe comparison is done because the statement is for a general-use-case (where num could be positive or negative), not for the specific case in his example program. If the whole point of the question was, "how do you round 4.9 to 5?" then we could just put
float num = 5.0
and be done with it. -
Alex S about 14 yearsI didn't say it can't possible work, I said it has no effect, by which I meant that removing the parentheses as you did doesn't change anything.
-
Tim Post almost 14 yearsThis produces 4 with ./gcc -frip-fabric-of-space-time. There's a plugin for emacs that turns this on by default.
-
Recurse almost 12 yearsWorse than that, by removing the brackets you have changed the type. The original expression had type int, yours has type float.
-
chux - Reinstate Monica over 7 yearsWhat you have posted does not compile in C - the language this post is tagged. Perhaps you are coding per another language?
-
chux - Reinstate Monica over 7 yearsFurther, in C++, using
int(...)
fails shouldx*(...)
exceed the range ofint
. -
chux - Reinstate Monica over 7 yearsThis methods fails when
num
is outside the range ofint
2) It would fail for many otherfloat
except that it usesdouble
math. e.g.(int)(num < 0 ? (num - 0.5f) : (num + 0.5f))
has many failing values whennum + 0.5f
rounds to afloat
result. -
chux - Reinstate Monica over 7 yearsNot a C solution.
int(x + 0.5)
is invalid C. Algorithm fails forx just less than 0.5,
x` not nearint
range. -
JJussi over 7 yearsIt's Arduino C/C++, sorry if that is not "real" C. There that int(float x) returns just integer (stripping decimals away). What is "right" way to strip just decimals away?
-
chux - Reinstate Monica over 7 yearsThe "right" way to strip decimals away from a
float
istuncf(x)
. -
Alex S over 7 years@chux when it's outside
int
range,float
can't distinguish between whole numbers and fractions anyway. Withdouble
, you can cast toint64_t
. -
chux - Reinstate Monica over 7 yearsYou comment may apply with on some platforms, but not in C in general. Consider 16-bit
int
. Quite common in embedded predecessors in 2016. -
chux - Reinstate Monica over 7 years
double trunc(double x)
is fordouble
. Usefloat truncf(float x);
forfloat()
. It can be computationally wasteful to use return afloat()
usingfloat x; return double trunc(x)
. -
Alex S over 7 years@chux sure, but I assume people working on weird hardware are already aware enough to figure this out for themselves.
-
chux - Reinstate Monica over 7 yearsEmbedded processors deployment in 2016 far exceed other platforms - Billions per years. Being so common is hardly weird. C is very popular there and many entering that field have trouble due to assumptions like
int
is 32-bits. -
Alex S over 7 years@chux then use int32_t.
-
chux - Reinstate Monica over 7 yearsYes code could use
int32_t
. OP's code though is aboutint
, notint32_t
and friends. Hence my comments relating toint
and a limitation with(int)(num < 0 ? (num - 0.5) : (num + 0.5));
.