Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round positive value half-up to 2 decimal places in C

Typically, Rounding to 2 decimal places is very easy with

printf("%.2lf",<variable>);

However, the rounding system will usually rounds to the nearest even. For example,

2.554 -> 2.55
2.555 -> 2.56
2.565 -> 2.56
2.566 -> 2.57

And what I want to achieve is that

2.555 -> 2.56
2.565 -> 2.57

In fact, rounding half-up is doable in C, but for Integer only;

int a = (int)(b+0.5)

So, I'm asking for how to do the same thing as above with 2 decimal places on positive values instead of Integer to achieve what I said earlier for printing.

like image 955
Truthseeker Rangwan Avatar asked Aug 03 '14 12:08

Truthseeker Rangwan


People also ask

What is 1.5 rounded 2 decimal?

Both 1.5 and 2.5 are rounded to 2 . 3.5 and 4.5 are rounded to 4 .

How do you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).


1 Answers

It is not clear whether you actually want to "round half-up", or rather "round half away from zero", which requires different treatment for negative values.

Single precision binary float is precise to at least 6 decimal places, and 20 for double, so nudging a FP value by DBL_EPSILON (defined in float.h) will cause a round-up to the next 100th by printf( "%.2lf", x ) for n.nn5 values. without affecting the displayed value for values not n.nn5

double x2  = x * (1 + DBL_EPSILON) ; // round half-away from zero
printf( "%.2lf", x2 ) ;

For different rounding behaviours:

double x2  = x * (1 - DBL_EPSILON) ;  // round half-toward zero
double x2  = x + DBL_EPSILON ;        // round half-up
double x2  = x - DBL_EPSILON ;        // round half-down
like image 161
Clifford Avatar answered Oct 31 '22 03:10

Clifford