Rounding up and down a number C++

The function you need is called round, believe it or not.

ceil rounds UP, btw. That is, to the closest larger integer. floor rounds down.


You don't need a function to round in C or C++. You can just use a simple trick. Add 0.5 and then cast to an integer. That's probably all round does anyway.

double d = 3.1415;
double d2 = 4.7;
int i1 = (int)(d + 0.5);
int i2 = (int)(d2 + 0.5);

i1 is 3, and i2 is 5. You can verify it yourself.


std::ceil 

rounds up to the nearest integer

std::floor 

rounds down to the nearest integer

std::round 

performs the behavior you expect

please give a use case with numbers if this does not provide you with what you need!

Tags:

C++

Ceil

Cmath