For example, I want 2.22 to round to 2 and 7.8 to round up to 8, and I want to use these values as integers later in my code to print out a certain number of asterisks. Turning them into int values rounds them down automatically, but I need a number to round up, how would I go about doing that?
Asked
Active
Viewed 217 times
-4
-
why do you do `cout << ...` if you want to round without displaying? google: "c++ rounding" – 463035818_is_not_an_ai Oct 13 '16 at 15:40
-
Streams. There is not only `cin` and `cout`. – LogicStuff Oct 13 '16 at 15:41
-
http://en.cppreference.com/w/cpp/numeric/math/round – Oct 13 '16 at 15:41
-
`cout << setiosflags(ios::fixed) << setprecision(0) << b << endl << c << endl;` does not do any rounding of the variables. It just displays them as rounded. If you need them rounded then you need to get a `round` function. – NathanOliver Oct 13 '16 at 15:41
-
are you looking for a string stream? – UKMonkey Oct 13 '16 at 15:43
-
This isn't the problem, but don't use `std::endl` unless you need the extra stuff that it does. `'\n'` ends a line. – Pete Becker Oct 13 '16 at 15:44
-
http://stackoverflow.com/questions/39925020/rounding-up-and-down-a-number-c/39925071#39925071 – brettmichaelgreen Oct 13 '16 at 15:45
1 Answers
1
You can use a round()
function, such as the one below, which works for positive numbers.
double round(double d)
{
return floor(d + 0.5);
}
You need the floor()
function for this, found in <cmath>
. I honestly cannot think of anything involving JUST <iostream>
and <iomanip>
EDIT: For another approach, use std::round()
, from <cmath>

Arnav Borborah
- 11,357
- 8
- 43
- 88
-
-
Rounding is much more complex than that. See https://en.wikipedia.org/wiki/Rounding#Tie-breaking . So your function covers too little of the possibilities, – Serge Rogatch Oct 13 '16 at 16:03