constant number size (double output)

How can I define a constant width of double numbers in an output file?
I use setprecision and scientific, but when there is a negative number the minus sign needs on space extra.

I would like a solution that one of the zeros is deleted when it is a negative numer or similar.

1
2
3
4
std::ofstream resultFile("Result.dat");

resultFile << std::setprecision(NUMBER_PRECISION) << std::scientific << Data.at(it_row) << "   ";


Output:

15 digits 15 digits 16 digits
1.04217000e+003 1.55950000e+001 -7.32260000e+002
1.08319000e+003 1.38020000e+001 -1.23905000e+003
1.11182000e+003 1.25860000e+001 -1.66787000e+003
1.13294000e+003 1.17060000e+001 -2.03544000e+003
1.14922000e+003 1.10390000e+001 -2.35399000e+003
1.16218000e+003 1.05160000e+001 -2.63272000e+003
1.17278000e+003 1.00950000e+001 -2.87867000e+003
1.18162000e+003 9.74740000e+000 -3.09728000e+003
1.18913000e+003 9.45650000e+000 -3.29288000e+003
1.19559000e+003 9.20910000e+000 -3.46893000e+003
Last edited on
you can use std::setw to save space for minus:
1
2
//change 16 to depend on NUMBER_PRECISION
resultFile << std::setprecision(NUMBER_PRECISION) << std::scientific << std::setw(16) << Data.at(it_row) << "   ";

Or you can look if number is negative and decrease precision by one in that case.
There are three ways I can think of:
1. show both'+' and '-' signs, this makes all the numbers the same width.
 
    cout << showpos;

2. instead of a '+', show a space. This can be achieved by specifying the field width:
 
    cout << setw(17) << number;

3. one of the zeros is deleted when it is a negative number - this means reducing the precision for negative numbers:
1
2
3
4
    if (number < 0.0)
        cout.precision(7);
    else
        cout.precision(8);
Thank you very much! Now I even have the choice how to do it.
Actually I recommend you to use setw() instead of outputting several spaces after each operation.
For example:
1
2
resultFile << std::setprecision(NUMBER_PRECISION) << std::scientific << 
              std::setw(NUMBER_PRECISION + 4) << std::left << Data.at(it_row);

Also note that you need to pass most manipulators only once:
1
2
3
4
5
//After opening file
resultFile << std::setprecision(NUMBER_PRECISION) << std::scientific << std::left /*<< std::showpos*/;

//In loop:
resultFile << std::setw(NUMBER_PRECISION + 4) << Data.at(it_row);
Last edited on
Topic archived. No new replies allowed.