Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent scientific notation in ostream when using << with double

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

when I do this

outfile << X;
like image 753
DogDog Avatar asked Feb 25 '10 16:02

DogDog


People also ask

How do I turn off scientific notation in C++?

you need to write: cout<< fixed; cout<< setprecision(2)<< f; fixed disables the scientific notation i.e. 1.23e+006.... and fixed is a sticky manipulator so u need to disable it if u want to revert back to scientific notation...

How to represent scientific notation in c++?

When floatfield is set to scientific, floating-point values are written using scientific notation: the value is represented always with only one digit before the decimal point, followed by the decimal point and as many decimal digits as the precision field (precision).

How do you set precision in C++?

By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.


4 Answers

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;
like image 106
davecoulter Avatar answered Oct 01 '22 11:10

davecoulter


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;
like image 33
Rozuur Avatar answered Oct 02 '22 11:10

Rozuur


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: http://www.cplusplus.com/reference/iostream/ios_base/fmtflags/

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

like image 32
matiu Avatar answered Sep 30 '22 11:09

matiu


you can use format flags   

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

like image 42
moogs Avatar answered Sep 30 '22 11:09

moogs