Rounding offto 2 decimal points

Hi, may I know how to round off a number to only 2 decimal points? For example, 2.789 becomes 2.79
2.43 become 2.4

Thanks in advance!
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:

#include <iomanip>
#include <iostream> 
  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.

#include <cmath> 
  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 (and its follow-up

Whew. Hope this helps!
Round to nearest integer, rounding halfway cases away from zero: std::round std::lround std::llround

Also see: std::nearbyint
std::rint std::lrint std::llrint
Wow, thank you very much!!!
Topic archived. No new replies allowed.