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

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

bump....

2. First you need to read the number with decimal places, so read in a float, not an int.

Then you can either just use std::setprecision to make the output operator do the rounding, or you can use a cast to int to cut away the decimal places. Since the latter always rounds down, though, you can add .5 first:
Code:
```float f1 = 3.2f;
int i1 = static_cast<int>(f1 + 0.5f); // -> 3.7 -> 3
float f2 = 3.7f;
int i2 = static_cast<int>(f2 + 0.5f); // -> 4.2 -> 4```

3. If your going to manually round it, CornedBee's suggestion will only work for positive numbers,
but incase you need to do it with a negative value, you can use this simple function.
Code:
```#define Abs(val)  ((val) < 0 ? -(val) : (val))
int round(float f) {
int abs_rounded = static_cast<int>( Abs(f) + 0.5f );
return (f < 0.0f ? -abs_rounded : abs_rounded);
}```
Hope this helps.

4. Ok here is the new one

float num;

cout<< "Please enter a positive value";

cin>> num=static_cast<int>(num + 0.5f);

cout<< num << endl;

5. cin>> num=static_cast<int>(num + 0.5f);
What exactly do you expect this line to do?

6. Originally Posted by CornedBee
What exactly do you expect this line to do?
Well the user will display a number and 0.5 is added to that number.

so if it's 3.1 it becomes 3.6, but since it's a interger it will round down to a 3.

That line is just to round the number and put it on the bottom line where is says:

cout<< num << endl;

7. Originally Posted by xbusterx
Well the user will display a number and 0.5 is added to that number.

so if it's 3.1 it becomes 3.6, but since it's a interger it will round down to a 3.

That line is just to round the number and put it on the bottom line where is says:

cout<< num << endl;
Yes, but you need to read the number first, then do the math, not all in one line.

--
Mats

8. Originally Posted by xbusterx
cin>> num=static_cast<int>(num + 0.5f);
There are a few problems with this line:
1)cin>> num evaluates to cin. This is so tht you can chain multiple >> together. But in this case that means you assign the value on the right to cin, not num.
2) you use num and change num in the same expression. Using a variable in this way is disallowed, except when the old variable is used to calculate it's new value, or when sequencing operators (&&, ||, ?:, and ,[comma]) seperate the two uses.
3)You also intended to change num twice in the same line. this is also disallowed, except again when sequencing operators are used.

As matsp said, break this expression into parts.