Re: Printing double value in a fixed size buffer
mathieu wrote:
I am trying to find a solution for the following problem: how do I
print in ASCII a double value in a fixed size buffer of 16 bytes ?
My first attempt was:
double data = 0.960000000000662;
std::cout << std::dec << std::setprecision(15) << data << std::endl;
Because it does not work for number matching "0.[0]*", I was
suggested:
std::cout << std::dec << std::setprecision(15) << std::fixed << data
<< std::endl;
This still does not work for:
double data = 1000000.960000000000662;
If your 'double' is like most of ours, then you have only 16 significant
digits, while here you typed 22! What you put in your program
double data = 1000000.960000000000662;
// 1234567 890123456 <--
is just a *string*. The conversion your compiler performs throws your
'00662' away anyway, most likely. The value in the running program does
*not* contain any information beyond
double data = 1000000.960000000;
for it to output. Of course it "doesn't work". You need an arbitrary
precision library to be able to use the 22 digits. Or you could try to
define the number 'long double', but there is no guarantee of the better
precision; for all we know the compiler implements 'long double' and
'double' exactly the same way (as it's allowed to).
and std::fixed is actually loosing all the precision for number such
as:
double data = 0.0000000000009654321;
Because 'fixed' is designed to actually consider the leading zeros as
significant. You seem to have conflicting requirements.
Could someone please let me know how I can use the iomanip functions
to solve my issue ? Requirements are:
- Up to a maximum of 16 bytes
- Only [0-9], 'e'/'E', '+'/'-' and '.' character can be used
- Minimize loss of information/precision
Try 'scientific' manipulator (the analog is the '%g' format in C).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask