0

I have this code:

double a = 7.456789;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;

and also this one:

double a = 798456.6;
cout.unsetf(ios::floatfield);
cout.precision(5);
cout << a;

the result of the first code is: 7.4568 Which is almost what I want (what I want to recieve is 7.4567) the result of the second : 7.9846e+05 Which is not at all what I want (I want 798456.6) I want to print the number till 4 numbers after the decimal point

How can I do that ?

John Oldman
  • 89
  • 2
  • 8
  • 1
    I don't think there's a standard way to change the rounding it does to print. You might be better off putting the number into a string. – chris Jan 01 '13 at 08:09
  • I was told I can use here in stf and precision in order to resolve this problem – John Oldman Jan 01 '13 at 08:11
  • Why do you want the number truncated? That can lead to loss of precision if it is used in additional processing. To get the result you want, compute the value as you want it and then print it. – wallyk Jan 01 '13 at 08:12
  • Well, you said you want a 7 instead of an 8. If there is a way to change that behaviour, I can't recall it, though if I recall correctly, boost has something of the sort. – chris Jan 01 '13 at 08:12

1 Answers1

4

By using unsetf(), you are telling cout to use its default formatting for floating-point values. Since you want an exact number of digits after the decimal, you should be using setf(fixed) or std::fixed instead, eg:

double a = ...;
std::cout.setf(std::fixed, ios::floatfield);
std::cout.precision(5);
std::cout << a;

.

double a = ...;
std::cout.precision(5);
std::cout << std::fixed << a;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770