How to make C++ cout not use scientific notation

Solution 1:

Use std::fixed stream manipulator:

cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;

Solution 2:

As mentioned above, you can use std::fixed to solve your problem, like this:

cout << fixed;
cout << "Bas ana: " << x << "\tSon faiz: " << t << "\tSon ana: " << x+t <<endl;

However, after you've done this, every time you print a float or a double anywhere in your project, the number will still be printed in this fixed notation. You could turn it back by using

cout << scientific;

but this might become tedious if your code gets more complicated.

This is why Boost made the I/O Stream State Saver, which automatically returns the I/O stream you're using to the state it was before your function call. You can use it like this:

#include <boost/io/ios_state.hpp> // you need to download these headers first

{
    boost::io::ios_flags_saver  ifs( os );

    cout << ios::fixed;
    cout<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;

} // at this bracket, when ifs goes "out of scope", your stream is reset

You can find more info about Boost's I/O Stream State Saver in the official docs.

You may also want to check out the Boost Format library which can also make your outputting easier, especially if you have to deal with internationalisation. However, it won't help you for this particular problem.

Solution 3:

code the next syntax:

std::cout << std::fixed << std::setprecision(n);

where (n) is the number of decimal precision. This should fix it.

P.s.: you need to #include <iomanip> in order to use std::setprecision.

Solution 4:

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("Bas ana: {:f}\tSon faiz: {:f}\t"
                         "Son ana: {:f}\n", x, t, x + t);

Output:

Bas ana: 3284.776791    Son faiz: 1784.776791   Son ana: 5069.553581
Bas ana: 7193.172376    Son faiz: 3908.395585   Son ana: 11101.567961
...

The advantage of this approach is that it doesn't change the stream state.

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("Bas ana: {:f}\tSon faiz: {:f}\tSon ana: {:f}\n", x, t, x + t);

Disclaimer: I'm the author of {fmt} and C++20 std::format.

Solution 5:

You can use format flags

More info: http://www.cplusplus.com/reference/iostream/ios_base/fmtflags/