I have a float that I would like to print to exactly N spaces. For example, with N = 5. I want to get the following numbers printed as so:
0.1 => 0.1
123.456789 => 123.5
-123.45678 => -123 (or -123.)
0.123456 => 0.123
123456.789 => 123456 (obviously, in this case, we cannot print less than 6 digits, if I can detect this, I can also print 12** to indicate the field is too wide.
I have tried many combination including the following:
// Leave 3 extra space: One for negative sign, one for zero, one for decimal
std::cout << std::setiosflags(std::ios::fixed)
<< std::setprecision(N - 3)
<< std::setw(N)
<< input;
But the results are not favorable. Perhaps I am missing something obvious?
The output of the given code for those sample inputs are
0.10 // not bad
123.46 // Use 6 instead of 5 spaces
-123.46 // Use 7 instead of 5 spaces
0.12 // Under-use the spaces
123456.79 // Ok, I guess
[UPDATE]
I should have tested for all cases provided. 😀