C++Introduction to C++Learn C++

Learn To Display Numbers With Formatting In C++ Software

When we use floating numbers, we sometimes need our C++ software to display them in a consistent way so we can compare numbers next to one another or with the preceding or successive numbers in an order. We can arrange formatting display of numbers both integer and precision side.

How can we format the display of numbers in C++? How can we use fixed, scientific or default formatting in C++ software? How can we use precision when formatting?

The precision of floating numbers (float , double, long double) can be arranged by the precision() function as given example below,

How do we format a number’s precision before output in C++?

We can use std::cout.precision() function before using cout as below,

here we #include <cmath> library to use pi constant M_PI. Output will be as here,

What about number formatting on output?

We can use std::setprecision() function when we use cout as below,

Using Specific Number Formatting in our C++ software

We can use std::fixed, std::scientific, std::hexfloat, std::defaultfloat to set format of floating numbers in our outputs. To use these I/O manipulators we need to #include <iomanip> library, We can set the printing format as below;

We can also use and change formatting with these I/O manipulators when using cout command. See full example below;

and the output will be as here,

How do we use fixed size formatting in C++?

We can fix the size of display by using std::setw() method. This fixed format with fixed size is the mostly used display in engineering results. See this C++ example below,

and the output will be,

How do we display matrix members with formatting in C++ software?

We can display matrix forms as below,

Note that we can use #include <limits> to get the maximum precision of a float or double.

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

About author

Dr. Yilmaz Yoru has 35+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux, and some other operating systems. He graduated and received his MSc and PhD degrees from the Department of Mechanical Engineering of Eskisehir Osmangazi University. He is the founder and CEO of ESENJA LLC Company. His interests are Programming, Thermodynamics, Fluid Mechanics, Artificial Intelligence, 2D & 3D Designs, and high-end innovations.
Related posts
C++C++17Language FeatureLearn C++

How To Use Skia Images in C++ Builder?

C++C++17Code SnippetGame DevelopmentLanguage FeatureLearn C++

What Is Skia In Modern C++?

C++C++17Learn C++

How To Use Skia in C++ Builder 12?

C++C++17C++20Introduction to C++Language FeatureLearn C++Syntax

Learn How To Use Clamp (std::clamp) In Modern C++ 17 and Beyond