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.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
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;
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
YOU show us some code.
Consider a proper using of floor() library function.
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
Lerner, check up your code again. It's wrong ;)...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
>>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.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
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)...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
That's incorrect: temp = (double)(i/10); . Integer division...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348