# (C++) How would I display a value rounded to the nearest integer?

1. Sep 21, 2008

### soul5

Like for example

Prompting message reads.

"Please enter a positive value"

Example:

Please enter a positive value: 234.7
Rounded to the nearest integer the number is: 235

Please enter a positive value: 10.3
Rounded to the nearest integer the number is: 10

What I have

int num;

cout<< "Please enter a positive value";

cin>> num;

cout<< num << endl;

The problem is that doesn't round the number to the nearest interger so what would I do to round it?

2. Sep 21, 2008

### rootX

(int) (3.5+0.5)

3. Sep 21, 2008

### soul5

Dude that's not it.

Last edited: Sep 21, 2008
4. Sep 21, 2008

### CRGreathouse

rootX gave a correct example of the calculation needed. You need to input as a float, not an int, then convert to an int by rounding as in rootX's suggestion.

5. Sep 21, 2008

### KTC

It does help if num is a floating point variable, rather than an int.

Round to zero (truncation)
Code (Text):
int rounded_num = static_cast<int>(num);
Round to +infinity
Code (Text):
int rounded_num = std::floor(num + 0.5);
Round away from zero
Code (Text):
int rounded_num = (num < 0.0)
? ((std::floor(num) == num - 0.5) ? std::floor(num) : std::floor(num + 0.5))
: std::floor(num + 0.5);
Really shouldn't do direct == with floating points, but that's another subject.

Or in C++0x:
Code (Text):
int rounded_num = std::round(num);
Round to even
Um, have fun....

6. Sep 26, 2008

### zyh

very insteresting, but I think rootx's answer is enough and simple.

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook