"Ingo Nolden" <in**********@SPAMrecurdyn.org> wrote in message
news:d6**********@svr7.m-online.net...
Hello,
I want to format floats ( doubles ) into small strings of 7 characters.
Not all required values of type 'float' or 'double'
can be represented by only 7 text characters. Do
you want those values truncated (and from which 'end'),
or are your values all within seven text characters,
or what? How many digits on either side of the decimal
do you want? IOW you don't give enough information.
I tried to use std::ostream, but I don't get the desired behaviour.
Especially in scientific notation I am not comfortable with things like
e+007. This is wasting 2 digits for the two zeros.
I didn't try boost::format, because it doesn't seem to me it will make any
difference on this. At least the documentation doesn't point it out.
Does anyone know a good way?
Once you've decided the answers to my above questions,
you can use a 'std::ostringstream' object with the manipulators
'std::fixed' and 'std::setprecision'. The former is declared
by <ios>, the latter by <iomanip>
#include <ios>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
int main()
{
double d (3.1416);
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << d;
std::cout << oss.str() << '\n'; /* prints 3.14 */
return 0;
}
Also, if you want to pad an output 'field' to a width
greater that the actual number of output characters
generated by <<, see the 'std::setw()' manipulator,
also declared by <iomanip>.
std::cout << '*' << std::setw(5) << "abc" << '*' << '\n';
/* prints *abc * */
(If the argument to 'setw()' is less than the number of
output characters generated by <<, the output width is *not*
truncated to that specified with 'setw()'.)
std::cout << std::setw(1) << "abc\n";
/* prints abc, not a */
-Mike