Formatting Support

Boost.Int128 supports formatting with both <format> (when C++20 and the header are both available), and . The following modifiers are listed in order of how they should be specified in the format string to be valid, and all information applies for both <format> and .

Fill and Alignment

You can specify alignment with an optional fill character. The format is [[fill]align] where:

Alignment Effect

<

Left-aligns the value within the available space

>

Right-aligns the value within the available space

^

Centers the value within the available space

The optional fill character (default is space) appears before the alignment character.

Examples:

Format Output for 42

{:<6d}

"42 " (left-aligned with spaces)

{:>6d}

" 42" (right-aligned with spaces)

{:^6d}

" 42 " (centered with spaces)

{:*<6d}

"42**" (left-aligned with asterisks)

{:0>6d}

"000042" (right-aligned with zeros)

{:*^6d}

"42" (centered with asterisks)

When no alignment is specified but a width is given (e.g., {:6d}), zero-padding is applied from the left.

Sign

There are three allowable signs first in the format string:

Sign Effect

+

Adds a + to positive values, and a - to negative values

-

Only adds a - to negative values

` ` (Space)

Adds a ` ` to positive values, and a - to negative values. Preserves alignment

Padding

You can then add any number of padding characters to make sure that a formatted value takes up a specified width (5 means minimum width of 5 characters and so on). Any integer value is accepted here.

Prepend Prefix

If you want to prepend the prefix to your number (if applicable) add #

Output Base Effect

Binary

0b or 0B

Octal

0

Decimal

None

Hex

0x or 0X

Output Base Modifiers

The following type modifiers are the same as those used by built-in integer values.

Modifier Format

b, B

Binary

o

Octal

d

Decimal

x, X

Hex

When the uppercase modifier is used, all characters will be capitalized (e.g. 0x2a vs 0X2A).

Default

The default format string {} will output the same as {:-d}, that is a decimal value which only has a sign if negative.

{fmt}

To use the {fmt} library, include <boost/int128/fmt_format.hpp> and <fmt/format.h>. The format specifiers described above work with fmt::format.

See the formatting example for a complete demonstration of these features.

<format>

To use std::format, include <boost/int128/format.hpp> and <format>. The format specifiers described above work with std::format.

The formatting example can be trivially modified by including <format>, and replacing all instances of fmt:: with std::