Skip to main content

Section 11.2 Formatting Numbers

Normally when you print out a floating point number, it will be printed with 6 significant digits (xxx.xxx or x.xxxxxx). This is not always what you want. For example, if you are printing out a currency value, you probably want to print out 2 digits after the decimal point. std::format provides tools to help us handle situations like these.
Formatting instructions are placed inside of the {} representing an item. The syntax is:
{:[[fill]align][sign]["#"][0][width][precision][type]}
Don’t panic! Each part is optional and most of the time you only need to specify one or two parts. We won’t worry about covering every possible option or every possible value for the options. If you ever need to, you can look up a std::format cheat sheet on the web.

Subsection 11.2.1 sign

By default, the sign of a number is only printed if it is negative. If you want to always print the sign, you can specify a + or in the [sign] location. Examine the spacing in this next program. _ is used around items to make it clear where spaces are being added by format:
Listing 11.2.1.

Subsection 11.2.2 precision

In the [precision] spot, a . followed by a number specifies a number of digits to include. By default, this is a count of significant digits (those to the left and right of the decimal place). When formatting 123.456789, an attempt to format to 2 decimal places will force the number to be written in scientific notation using just 1.2. 3 digits will result in no decimal. 4+ will allow for some decimal places:
Listing 11.2.2.
Often times, what we really want to specify is a number of decimal places to print. To do that, we need to add on a [type] specifier. In this case, we want the type f for β€œfixed point”. We can also use e to specify that we want to force scientific notation.
Listing 11.2.3.

Subsection 11.2.3 type

In addition to using f and e in the [type] spot to control the formatting of doubles, we can use it to force numeric (or potentially numeric) values to output in another format:
Listing 11.2.4.

Checkpoint 11.2.1.

You have attempted of activities on this page.