Site icon 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,

[crayon-663a7efe91663381468185/]

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

[crayon-663a7efe9166a629244377/]

What about number formatting on output?

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

[crayon-663a7efe9166c166791349/]
[crayon-663a7efe9166e084640753/]

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;

[crayon-663a7efe91670736162947/]

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

[crayon-663a7efe91676134879042/]

and the output will be as here,

[crayon-663a7efe91678898213479/]

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,

[crayon-663a7efe9167b644046995/]

and the output will be,

[crayon-663a7efe9167d997924950/]

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

We can display matrix forms as below,

[crayon-663a7efe9167e387045435/]

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

Exit mobile version