简体   繁体   中英

Rounding to second decimal place unless the number is whole c++

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.

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:

  • Write 2.5 instead of 2.50
  • Write 3.14 for 3.1421783921, rather than 3.15

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM