Output Streams

Formatting Floating-Point Numbers

How can I format numbers in scientific notation using C++ output streams?

Abstract art representing computer programming

Formatting floating-point numbers in scientific notation using C++ output streams is straightforward with the help of manipulators like std::scientific and std::setprecision().

Using 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.

Adjusting 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.

Combining with Other Manipulators

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

Resetting to Default

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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved