im trying to learn how to make a if/then statement that will take a number, possibly with a decimal and round it to the nearest integer. Like so..

if 3.4 is the number, then the final would be 3 not 3.4

how would i do so?

4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by ArkM

Rounding a number to the nearest whole number is one of the easiest things you can do in C++ :) there isn't even any need for an if/else statement, take this as an example.

``````float decimal = 3.4f;
int rounded = int(decimal + 0.5f); // 3``````

Hope this helps.

Yes it does. Thank you.

I wasnt the one who posted the question, but I am workin on a program that has a sim problem. Its a calculater that that works out the ultimate return on a purchase. I am writing it for an MMORPG I play.

This was a big help, thnk you. =]

1. Regrettably, for negative numbers williamhemsworth's solution does not work (moreover, gives wrong result - for example, it yields 0 for -0.9 but nearest integer value for -0.9 is -1). Right solution:

``````#include <cmath>
...
double round(double x) {
bool negative = false;
if (x < 0.0) {
x = -x;
negative = true;
}
x = std::floor(x+0.5);
return negative? -x: x;
}``````

2. In this context a rounding to the nearest integer is not the same thing as a rounding to the nearest int type value. For example, on 32-bit CPU max int is 2147483647 (INT_MAX macros from limit.h). So you can't round 3333333333.3 to int 3333333333 (no such int value) - but you can round it to 3333333333.0. Of course, if you want to round to int, you may use the same method as in round function defined above (no need in floor library call in that case).