The std::format
function and related formatting functions allow you to control how to display a value as text, including its width and
precision.
For example, you can convert the number 3.14159
to a string with a minimum width of 10
and a precision of 2
using:
std::format("{:_>10.2f}", 3.14159)
The format string uses:
-
_
as the padding character
-
>
to align the value to the right
-
10
to specify the width
-
.2
to specify the precision
-
f
to use the fixed decimal notation
The resulting string is "______3.14"
.
Furthermore, there are two ways to specify the width and the precision:
On the one hand, using static values is safe and predictable but not very flexible. On the other hand, using dynamic values can result in runtime
exceptions and unexpected program termination.
Specifically, a std::format_error
exception is thrown when a dynamic value for the width or the precision specifiers is either
negative or not a built-in integer.