Hey guys, this function is for rounding 2 decimal places, e.g. 1.2785 rounds to 1.2800. First, how would I alter the function so it would round 3 decimal places 1.2780, and second how would I truncate it so it would read 1.278.

Thanks!

double roundIt(double x, double n)  //Write definition for rounding function
{ 
    x = floor( x * pow(10.0, n) + 0.5) / pow(10.0, n);
    return x;
}

Recommended Answers

All 5 Replies

play around with the value of n and see what happens. In particular, try changing n from 1 to 2 to 3 etc. The function as written isn't specific for rounding to 2 decimal places.

Also, look into the stream manipulators, and here I'm thinking of the fixed and setprecision manipulators, to determine how many decimal points to display.

commented: very helpful +1

Take into account that it's impossible to round decimal fractions accurately with binary floating point data ;)
Try to avoid pow function using: it's the most ineffective and inaccurate method in that case.

well at the first place i would recommend usage of float data type instead on double , guess float would do the trick.
second of all subtract the left part of the no from the original no itself , by doin this u can isolate the decimal part and then if u r looking for a 3 decimal round off in all the nos ( which apparently is ) .
u can multiply the 3 digits decimal into 100 and then round of them

float round( float no )
{
     int x, temp;
     float y;
     temp = x = no ;   only the integer part is taken 
     y = no -  x ; u get the decimal number here 
     y*=100 ; decimal gets converted to 2 digit no n 1 decimal
     x = y;
     y-= x;  the last decimal is stored in y 
     if( y > = 0.5 )
             x++ ;
    return (temp + x/100) ;
}

well i would like you to dry run the code .

commented: very helpful +1

NEVER use float data type in math and financial calculations, it has too low precision. Standard C and C++ floating point type is double (have a look at <cmath> header contents).

Use modf library function to separate integer and fractional parts.

commented: very helpful +1

thanks guys! I am trying to incorporate this in a weird kinda of assignment, I may need to get with you later. I will go ahead mark as solved. As always I throw myself at your wisdom! :icon_cheesygrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.