std::format
and the related formatting functions provide two different options to pad numerical values up to a specific width:
- Custom character padding: this option can align text to the left, center, or right using any character.
For example,
std::format("{:*>5}", num)
aligns num
to the right (>
) by inserting *
characters until it
reaches a width of 5.
- Numeric padding with
0
: this option is available for most arithmetic types and is enabled by adding 0
before the
width specifier.
For example, std::format("{:05}", num)
adds enough 0
before num
to align it to the right
and reach a width of 5.
0
can also be used as a custom character padding, but this syntax is confusing and may produce unexpected results when aligning
negative values to the right:
// Noncompliant: character padding results in "00-10"
std::format("{:0>5}", -10) // "0" is a custom character padding here.
// Compliant: numeric padding results in "-0010"
std::format("{:05}", -10) // The ">" was removed; "0" now means numeric padding.