Solved

# decimal rounding

Posted on 1998-12-12
Medium Priority
296 Views
What's the easiest way to round (or truncate) a double value?

example:

I have   3.21453235
I want   3.21

Thanks
0

LVL 1

Accepted Solution

MatthewL earned 100 total points
ID: 1180028

You can shift the number the required number of decimal places, truncate it, and shift it back again.  The function round listed below does that.  It has a limitation on the size of the numbers used ( since I've cast into a long int ).

Matt

#include <iostream.h>
#include <math.h>

double round( double number, int decPlace );

void main( void )
{
double value = 3.21453235;

value = round( value, 2 );

cout << value << endl;

}

double round( double number, int decPlace )
{
long int temp;

number *=  pow( 10, decPlace );
temp = (long int)( number + .5 );
number = ( double ) temp;

number /= pow( 10, decPlace );

return( number );
}
0

LVL 85

Expert Comment

ID: 1180029
Now try it with
value = round( -3.21453235, 2);
0

LVL 22

Expert Comment

ID: 1180030
To avoid the limitations of 32 bit integers and (I believe) to have the correct (well, most accepted) rounding for negatives, use

number *=  pow( 10, decPlace );
number = floor( number + .5 );
number /= pow( 10, decPlace );
0

Expert Comment

ID: 1180031
iff this is for printing the value you can just use the width and precision stuff for printf.
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.