How to Make C++ Cout Not Use Scientific Notation

How to make C++ cout not use scientific notation

Use std::fixed stream manipulator:

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

Conversion of string to double without scientific notation in C++

The scientific notation has to do with std::cout, not the way the value is stored, so you must use std::fixed before you print the value:

std::cout << std::fixed << std::setprecision(2) << d << std::endl;

As you can see in the demo, this works fine, it should work for you as well.

As @goodvibration commented std::to_string also works but it's not possible to redefine, in a simple manner, the default number or decimal places in this case.

std::cout << std::to_string(d) << std::endl;

Live demo

Prevent scientific notation in ostream when using with double

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;

Getting rid of Scientific Notation C++

Use the std::fixed stream manipulator (http://en.cppreference.com/w/cpp/io/manip/fixed)

How to print precise digits after E in scientific notation in c++

You can't set the number of digits of the outputted exponent in scientific notation using the standard manipulators in C++.

One thing you could do is to remove or add a '0' to the resulting string, if needed.

#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <algorithm>

int main()
{
double c = 106.895;
std::stringstream ss;
ss.setf(std::ios_base::scientific | std::ios_base::uppercase);
ss << std::setprecision(9) << c;
auto number = ss.str();

// you can add the '0' if needed
size_t pos = number.size() - 3;
if ( !std::isdigit(int(number[pos])) )
{
if ( number[pos] == 'E' )
number.insert(pos + 1, "+0");
else
number.insert(pos + 1, 1, '0');
}

std::cout << number << '\n'; // --> 1.068950000E+002

// Or remove it
size_t pos_0 = number.size() - 3;
if ( number[pos_0] == '0' )
number.erase(pos_0, 1);
std::cout << number << '\n'; // --> 1.068950000E+02
}


Related Topics



Leave a reply



Submit