简体   繁体   中英

How to return a "double" value to two decimal places in C++

double calc_percent_of_daily_sugar(int sugar) {
  double result;
  result = sugar/avg_sugar_intake;
  return result*100;
}

I'm trying to get this function to return the result to only 2 decimal places however when I try to use cout << setprecision(2) << result; then there are still more than 2 places in the number Apologies if this is a nooby or stupid question.

*How to print a “double” value to two decimal places in base 10 in C++

Use std::fixed to print it in decimal.

std::cout << std::setprecision(2) << std::fixed << 123.4567 << std::endl;
// 123.46   

See: https://en.cppreference.com/w/cpp/io/manip/fixed

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