c++decimalformat

Displaying decimals only if they are not equal to 0. C++


My doubles are:

32943.14
55772.04
15310.58

My output should be:

32943.1
55772
15310.6

I tried the following:

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    
    double numbers[3] = { 32943.14, 55772.04, 15310.58 };
    
    for(int i = 0; i < 3; i++){
        cout << setprecision (1) << fixed << numbers[i] << endl;
    }

    return 0;
}

It did not work. What is the best way to get required output?


Solution

  • If you actually assign the result to a double variable, you get the desired output.

    #include <iomanip>
    #include <iostream>
    #include <sstream>
    
    using namespace std;
    
    int main() {
      double numbers[3] = {32943.14, 55772.04, 15310.58};
      for (int i = 0; i < 3; i++) {
        stringstream ss;
        ss << fixed << setprecision(1) << numbers[i];
        double n = stod(ss.str());
        cout << n << endl;
      }
      return 0;
    }
    

    Remember that fixed << setprecision(1) are only formatting the numbers[i] to be displayed. If you then turn the formatted string, e.g., "123.0" back to a double, then it is automatically printed as 123.