Formatting floating-point numbers in scientific notation using C++ output streams is straightforward with the help of manipulators like std::scientific
and std::setprecision()
.
std::scientific
To format a number in scientific notation, you can use the std::scientific
 manipulator:
#include <iostream>
int main() {
double pi = 3.141592653589793;
std::cout << std::scientific << pi;
}
3.141593e+00
This converts the number into scientific notation with a default precision.
You can control the number of digits displayed after the decimal point using the std::setprecision()
manipulator from the <iomanip>
 header:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589793;
std::cout << std::scientific
<< std::setprecision(3)
<< pi;
}
3.142e+00
Here, std::setprecision(3)
sets the precision to three digits after the decimal point.
You can combine std::scientific
with other manipulators for more complex formatting. For example, if you want to set a fixed width for the output, you can use std::setw()
and std::setfill()
:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589793;
std::cout << std::scientific
<< std::setprecision(2)
<< std::setw(15)
<< std::setfill('_')
<< pi;
}
_______3.14e+00
To revert to the default floating-point notation, you can use std::defaultfloat
:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589793;
std::cout << std::scientific << pi << '\n';
std::cout << std::defaultfloat << pi;
}
3.141593e+00
3.14159
Understanding how to use these manipulators allows you to present floating-point numbers in the most appropriate format for your application.
Answers to questions are automatically generated and may not have been reviewed.
A detailed overview of C++ Output Streams, from basics and key functions to error handling and custom types.