Pls suggest the code so that the value 9.8754321 is exactly displayed without any truncation? Dont use manipulator or printf function. It is expected to use only formatting flags.

Code:

int main()

{

float i=9.8754321 ;

cout<<i;

}

Printable View

- 09-29-2009forumuserDisplaying 9.8754321 exactly using cout and format flags
Pls suggest the code so that the value 9.8754321 is exactly displayed without any truncation? Dont use manipulator or printf function. It is expected to use only formatting flags.

Code:

int main()

{

float i=9.8754321 ;

cout<<i;

}

- 09-29-2009Dae
- 09-29-2009forumuser
setprecision is a manipulator and hence this is not the required solution.

- 09-29-2009laserlightQuote:

Originally Posted by**forumuser**

- 09-29-2009anon
I don't think this can be done with format flags alone.

You could print the integral and decimal part separately as integers (e.g use fmod from cmath to get the decimal part, multiply it by 10000000 and round to integer).

As a general case, floating point representation has no notion of "digits". It is just a binary approximation of the value. - 09-29-2009forumuser
Is there any formatting flag that makes it possible to print decimal values with required precision?

- 09-29-2009laserlightQuote:

Originally Posted by**forumuser**

Code:`std::cout.precision(8);`

- 09-29-2009punkywow
sorry but why u dont use printf("%f",float); to express your float?

- 09-29-2009laserlightQuote:

Originally Posted by**punkywow**

2. It will not help anyway (but then the question is flawed to begin with). - 09-30-2009iMalc
This is probably going to come as a total shock, and you might even be tempted to not believe it at first, but the variable "i"

**does not**contain the value 9.8754321 in that piece of code. A float is**an approximation**which only holds about 6 significant figures. You can try and assign it a number with as many digits to the right of the decimal point as you like but the actual number it holds will only contain about 6 significant figures. In the above case "i" is 9.875432**0**on a typical PC, and that's actually quite lucky, as often the number will be even less accurate than that.

What Every Computer Scientist Should Know About Floating-Point Arithmetic