Prevent scientific notation in ostream when using << with double
Asked Answered
C

4

42

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

when I do this

outfile << X;
Cort answered 25/2, 2010 at 16:31 Comment(1)
Related for other languages: Haskell Lua C++ ostreams DelphiHeadon
A
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;
Astereognosis answered 25/2, 2010 at 17:28 Comment(2)
What makes you think that showpoint makes any difference here? The decimal portion is always shown with 0's due to the precision.Gamic
All I needed was to include <iomanip> and use setprecision(n)Frey
A
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;
Allerus answered 25/2, 2010 at 16:43 Comment(1)
Better answer since it directly answers the question ('fixed').Inquiring
B
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

Bewray answered 7/10, 2013 at 10:17 Comment(1)
Can't edit right now, but that gives a 404. Try en.cppreference.com/w/cpp/io/ios_base/fmtflags (thanks Moogs)Gaze
T
2

you can use format flags   

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

Twosided answered 25/2, 2010 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.