Anyone have any idea how I would write a program that lets user input a floating point number and then either round up if number is like 4.5 our round down(truncate) if number like 4.49. Any help would be greatly appreciated.

9 Years
Discussion Span
Last Post by ArkM

There are several ways that can be done. One way is to add 0.5 (or a similar value depending on where you want to round) to the original value and then cast it to an int and then back again if you want to round to the nearest decimal value place holder.


WARNING:Code based on my logic. Not compiled and tested in reality.

//round to closest integer.
double d = 2.49;
int i = (int)(d + 0.05);
cout << i << endl;

d = 2.51;
i = (int)(d + 0.05);
cout << i << endl;

//round to closest tenth (on first decimal point)
d = 2.41;
double temp = d * 10;
i = (int)(temp + 0.5);
temp = (double)(i/10);
cout << temp << endl;

d = 2.47;
temp = d * 10;
i = (int)(temp + 0.5);
temp = (double)(i/10);
cout << temp << endl;

double RoundDouble(double doValue, int nPrecision)
       static const double doBase = 10.0;
       double doComplete5, doComplete5i;

       doComplete5 = doValue * pow(doBase, (double) (nPrecision + 1));

       if(doValue < 0.0)
               doComplete5 -= 5.0;
               doComplete5 += 5.0;

       doComplete5 /= doBase;
       modf(doComplete5, &doComplete5i);

       return doComplete5i / pow(doBase, (double) nPrecision);

Edited by Nick Evan: Fixed formatting


>>Lerner, check up your code again. It's wrong

Yup; looks like this,

i = (int)(d + 0.05);

should be this:

i = (int)(d + 0.5);

Any other (il)logic errors (and there may be some) will need to wait for me to check it with a compiler. The theory remains intact even if I stub my toe, though. Thanks for pointing out my error!

There are certainly other ways to round and I suspect that using any of the other approaches already suggested and those yet to be suggested will also work.


Use modf() function to splt integer and fractional parts of the double value before other operations (change a sign of negative value before other stuff then restore right sign after rounding). You lost some precision and may catch overflow with direct multiplication. Have a look to addition of 0.5 in Lerner's post (no need in if-else).
Using (twice) of relatively slow pow function is not the best idea. Consider another approach(es)...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.