Reputation: 1205
I am trying to print the average in Cpp up to 2 decimal points of the float
num. avg
is float
, sum
is float
, count
is int
.
Currently if I have 10/1 for example it outputs 10.00. I want the output to be just 10. if avg
gets value 3.1467665
for example, it should be displayed as 3.14
.
avg = sum/count;
std::cout << std::fixed << std::setprecision(2) << avg;
The rounding should be just for the output. No need to change avg
but if it is easier, its value can be changed.
Looking for a solution using a standard before c++11.
UPD: the output is 27.50 when I want it to be 27.5.
Upvotes: 0
Views: 223
Reputation: 8491
You could choose precision according to the floating modulus of the avg
value. The following works:
int main() {
double sum = 10;
double count = 3;
double avg = sum/count;
double mod;
std::cout << std::fixed
<< std::setprecision((modf(avg, &mod) != 0.0) ? 2 : 0)
<< avg
<< std::endl;
}
Considering the added specifications:
Here is a possible implementation using @IInspectable's suggested method:
std::stringstream ss;
ss << std::fixed << avg;
size_t pos = ss.str().find('.');
if (pos + 2 < ss.str().size()) // If there is a '.' and more than 2 digits after it
pos += 3;
std::string s = ss.str().substr(0, pos); // Leave only two digits
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return ch != '0'; }).base(), s.end()); // Remove trailing zeros
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return ch != '.'; }).base(), s.end()); // Remove trailing '.' when needed
std::cout << s << std::endl;
This will output:
10/4 -> 2.5
10/3 -> 3.33
10/2 -> 5
10/7 -> 1.42
3.9999 -> 3.99
Upvotes: 3