std::dec << std::setprecision(15)

M

mathieu

Hi there,

I am trying to only display up to a maximum of 16 characters from a
double value. the following piece of code works fine most of the time,
except in some case:

#include <iostream>
#include <iomanip>

int main(int, char *[])
{
double data1 = 1.960000000000662;
double data2 = 0.960000000000662;
std::cout << std::dec << std::setprecision(15) << data1 <<
std::endl;
std::cout << std::dec << std::setprecision(15) << data2 <<
std::endl; // 17 char displayed

return 0;
}

Is there something equivalent to setprecision but which could handle
this case ? Or do I need to handle the "0.*" case and the case where
the value if negative ?

Thanks
 
J

James Kanze

I am trying to only display up to a maximum of 16 characters
from a double value. the following piece of code works fine
most of the time, except in some case:
#include <iostream>
#include <iomanip>
int main(int, char *[])
{
double data1 = 1.960000000000662;
double data2 = 0.960000000000662;
std::cout << std::dec << std::setprecision(15) << data1 <<
std::endl;
std::cout << std::dec << std::setprecision(15) << data2 <<
std::endl; // 17 char displayed

return 0;
}
Is there something equivalent to setprecision but which could
handle this case ? Or do I need to handle the "0.*" case and
the case where the value if negative ?

The (minimum) number of characters to display is handled by
width, not precision. And std::dec has no effect on floating
point output whatsoever (and is the default). However...

What format do you want to use for display? By default, the
format depends on the value, and precision is the number of
significant digits. Other alternatives are fixed and
scientific, where in both cases, precision signifies the number
of digits after the decimal. If I modify the code to use fixed
and scientific, as well (and to output a '|' before and after
the number, so what is generated by the output is clearly
identifiable), I get:

default:
|1.96000000000066|
|0.960000000000662|
fixed:
|1.960000000000662|
|0.960000000000662|
scientific:
|1.960000000000662e+00|
|9.600000000006620e-01|

The question is, of course, which one you want. (Note that the
differences could be even greater if you use different values.
For some vaules, the default format will toggle to
scientific---but always with precision meaning the number of
digits, and not the number of digits after the decimal.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,968
Messages
2,570,152
Members
46,697
Latest member
AugustNabo

Latest Threads

Top