| re: formatting floating numbers into 7 digits?
Mike Wahler wrote:[color=blue]
> "Ingo Nolden" <ingo.noldenN@SPAMrecurdyn.org> wrote in message
> news:d67tdt$oht$1@svr7.m-online.net...
>[color=green]
>>Hello,
>>
>>I want to format floats ( doubles ) into small strings of 7 characters.[/color]
>
>
> 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'),[/color]
yes, of course and from the end that produces the least error[color=blue]
> 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.
>[/color]
Ok, I'll try. I want it to print a value with the highest possible
accuracy within a maximum of 7 characters.
eg:
1234567890123344.123 -> 1.23e15
0.000000000012345678 -> 1.2-e11
1.0 -> 1.0 ( or maybe 1 or 1. )
0.123 -> 0.123
[color=blue]
>[color=green]
>>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?[/color]
>
>
> 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 */
>[/color]
yes, it works well if the output is smaller than my 7 digits, but if
scientific notation is necessary to represent my number as accurate as
possible, it will use more than 7 digits, and it will also waste digits
with leading zeros in the exponent.
[color=blue]
> -Mike
>
>[/color]
I really appreciate your help
Ingo |