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

143 Views Asked by At

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?

2

There are 2 best solutions below

1
scribe On BEST ANSWER

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.

1
David C. Rankin On

If you don't mind using <cstdio> simply outputting with %g will do what you want. Without a precision for %g, it is taken as 1 and only non-zero decimals are output, e.g.

#include <cstdio>

int main() {
    
    double numbers[3] = { 32943.14, 55772.04, 15310.58 };
    
    for (int i = 0; i < 3; i++){
        printf ("%g\n", numbers[i]);
    }
}

Example Use/Output

Compiled with:

 g++ -Wall -Wextra -pedantic -std=c++20 -Ofast -o bin/precision1-if-nonzero-stdio precision1-if-nonzero-stdio.cpp
$ ./bin/precision1-if-nonzero-stdio
32943.1
55772
15310.6

(not to mention the assembler code being 1800% smaller...)