42

I need to prevent my double to print in scientific notation in my file,

when I do this

outfile << X;
gsamaras
  • 71,951
  • 46
  • 188
  • 305
DogDog
  • 4,820
  • 12
  • 44
  • 66
  • 1
    Related for other languages: [Haskell](http://stackoverflow.com/questions/8098457/how-do-i-get-to-haskell-to-output-numbers-not-in-scientific-notation) [Lua](http://stackoverflow.com/questions/1133639/how-can-i-print-a-huge-number-in-lua-without-using-scientific-notation) [C++ ostreams](http://stackoverflow.com/questions/2335657/prevent-scientific-notation-in-ostream-when-using-with-double) [Delphi](http://stackoverflow.com/questions/6077153/how-to-disable-scientific-notation-in-asstring-in-delphi) – Mechanical snail Aug 22 '12 at 03:39

4 Answers4

40

To set formatting of floating variables you can use a combination of setprecision(n), showpoint and fixed. In order to use parameterized stream manipulators like setprecision(n) you will have to include the iomanip library:

#include <iomanip>

setprecision(n): will constrain the floating-output to n places, and once you set it, it is set until you explicitly unset it for the remainder of the stream output.

fixed: will enforce that all floating-point numbers are output the same way. So if your precision is set to 4 places, 6.2, and 6.20 will both be output as:

6.2000
6.2000

showpoint: will force the decimal portions of a floating-point variable to be displayed, even if it is not explicitly set. For instance, 4 will be output as:

4.0

Using them all together:

outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
davecoulter
  • 1,806
  • 13
  • 15
10

Here's an example of usage http://cplus.about.com/od/learning1/ss/clessontwo_4.htm

as per your question use

  std::cout << std::fixed << a << std::endl;
Community
  • 1
  • 1
Rozuur
  • 4,115
  • 25
  • 31
6

All the above answers were useful, but none directly answer the question.

outfile.setf(std::ios_base::fixed);
outfile << x;

I found the answer in @moogs link: https://en.cppreference.com/w/cpp/io/ios_base/fmtflags

Here's a demo program: http://ideone.com/FMxRp1

matiu
  • 7,469
  • 4
  • 44
  • 48
  • Can't edit right now, but that gives a 404. Try http://en.cppreference.com/w/cpp/io/ios_base/fmtflags (thanks Moogs) – John P Nov 11 '22 at 21:45
2

you can use format flags   

http://en.cppreference.com/w/cpp/io/ios_base/fmtflags

moogs
  • 8,122
  • 8
  • 44
  • 60