That is a straight-forward question.
Unfortunately, there is no straight-forward answer. This is because “rounding” and FP numbers are not simple issues.
If all you want to do is
print a number that is half-up rounded at some arbitrary fractional place, use the stream manipulators:
1 2
|
#include <iomanip>
#include <iostream>
|
1 2 3 4
|
some_stream << std::fixed << std::setprecision( 2 );
some_stream << 3.141592; // prints "3.14"
some_stream << 2.789; // prints "2.79"
some_stream << 2.799; // prints "2.80"
|
However, if you want to actually modify the numeric value, you'll need to multiply, round, and divide.
1 2
|
double x = 2.789;
double rounded = std::floor((x * 100) + .5) / 100;
|
The caveat is that this might not do exactly what you think. The reason is that floating point numbers are not exact. And the reason for
that is twofold: (1) numbers in the computer are represented in binary but we view them in decimal, which is a conflict when dealing with exact digit place value, and (2) FP numbers sample a range of values in a discrete space; they are not continuous. (Said another way, there are gaps between numbers. This is reasonable: a 64-bit value only has 18,446,744,073,709,551,615 possible values, which are divided among the mantissa and exponent and sign fields, and is far fewer numbers than the infinite available between any two real values, like 0 and 1. There are other reasons too, but these listed ones are the major players.)
So in other words, once you round like that, the computer might actually be storing a slightly different number: the one it can represent that is
closest to the actual value.
For rounding methods, check out
http://www.cplusplus.com/forum/articles/3638/ (and its follow-up
http://www.cplusplus.com/articles/213hAqkS/).
Whew. Hope this helps!