C++20 Formatting: Part-5 Precision and Alternate formatting

Gajendra Gulgulia
6 min readMar 10, 2023

In the fourth part of the series on formatting library, we looked at formatting number of integral and floating point types. Further with examples we saw how different type specifier for floating point number have different default precisions for hexadecimal, scientific, fixed and general types.

In this tutorial we will see how

  1. to control the precision of the floating point numbers in the formatting library.
  2. How to use the alternate format specifier ( #)

Since precision applies only to floating point numbers (and strings) this tutorial will consider only floating point numbers for purpose of precision of numbers.

1. Precision

To specfiy the precision in the format specifier, one needs to precede the precision with . For e.g. if the width format specifier is 8 and the precsion format specifier is 5, then the format specifier looks like {:8.5} .

If there’s no width format specifier and only the precision format specifier of 5, then the format specifier looks like {:.5} .

1.1 Static Precision specification

This is done by specfying the non negative precision number in the placeholder after the colon followed by…

--

--

Gajendra Gulgulia
Gajendra Gulgulia

Written by Gajendra Gulgulia

I'm a backend software developer and modern C++ junkie. I run a modern cpp youtube channel (https://www.youtube.com/@masteringmoderncppfeatures6302/videos)

No responses yet