# Thread: Rounding up or down accordingly...

1. ## Rounding up or down accordingly...

how do you do it?

I want to round up if the value is .5+, and down if .49 or less.

2. preferably in an elegant way...

short code looks pretty.

3. round().

Unless you're on some compiler that hasn't gotten up to 1999, in which case you have to trunc(number+0.5).

4. how do you use it?

is there a guide here on the forum?

thnkx

5. Do you have a C book, or reference of some kind? They're "built-in" functions (library functions, really, but close enough).

Anyway, they're in <math.h>.

6. Originally Posted by tabstop
Anyway, they're in <math.h>.
Not according to cplusplus.com

QuantumPete

7. Originally Posted by ISO C99
7.12.9.6 The round functions
Synopsis
1 #include <math.h>
double round(double x);
float roundf(float x);
long double roundl(long double x);
Description
2 The round functions round their argument to the nearest integer value in ﬂoating-point
format, rounding halfway cases away from zero, regardless of the current rounding
direction.
Returns
3 The round functions return the rounded integer value.
And I guess trunc is C99 only, too, it's floor that's in C89.
Originally Posted by ISO C99
7.12.9.8 The trunc functions
Synopsis
1 #include <math.h>
double trunc(double x);
float truncf(float x);
long double truncl(long double x);
Description
2 The trunc functions round their argument to the integer value, in ﬂoating format,
nearest to but no larger in magnitude than the argument.
Returns
3 The trunc functions return the truncated integer value.

8. Alternatively, you could use ceil and floor..

Code:
```double n = 23.45, floorDiff = n - floor(n), ceilDiff = ceil(n) - n;

if(floorDiff < ceilDiff)
n = floor(n);
else
n = ceil(n);```

9. And if you do this "a lot", you could optimize the calls to ceil/floor by doing:
Code:
```double n = 23.45, nFloor = floor(n), nCeil = ceil(n);
double floorDiff = n - nFloor, ceilDiff = nCeil - n;

if(floorDiff < ceilDiff)
n = nFloor;
else
n = nCeil;```
Whether that is worth it or not depends a bit on the actual implementation of floor() and ceil(), as they may not be "true functions", in which case the overhead is much smaller than if they are real functions.

--
Mats

10. Originally Posted by IceDane
Alternatively, you could use ceil and floor..
True, but wouldn't this be better:
Code:
```float n = 23.45
n = (float) ((int) (n+0.5));```
QuantumPete