Formating support

Boost.Decimal supports formatting with both <format> (when C++20 and header are both available) and <fmt/format.h>.

<format>

Format is supported when using C++20 and a compiler with appropriate support: GCC >= 13, Clang >= 18, MSVC >= 19.40

Type Modifiers

The following type modifiers are the same as those used by built-in floating point values:

Modifier

Format

"g" or "G"

General

"e" or "E"

Scientific

"f"

Fixed

"a" or "A"

Hex

Example usage for scientific format would be: {:e}

The uppercase format will return with all applicable values in uppercase (e.g. 3.14E+02 vs 3.14e+02)

Precision Modifiers

Precision can be specified in the same way as built-in floating point values. For example a scientific format with 3 digits or precision would be: {:.3e}

Padding Modifiers

If you want all values to be printed with a fixed width padding is allowed before the precision modifier. For example with {:10.3e}:

  • 3.14 → " 3.140e+00"

  • 3.141 → " 3.141e+00"

Note the space at the front of these string to keep with width at 10 characters

Examples

The example is padding modifiers can be done like so

#include <boost/decimal.hpp> // or <boost/decimal/format.hpp>
#include <format>
#include <iostream>

int main()
{
    constexpr boost::decimal::decimal64_t val1 {314, -2};
    constexpr boost::decimal::decimal32_t val2 {3141, -3};

    std::cout << std::format("{:10.3e}", val1) << '\n';
    std::cout << std::format("{:10.3e}", val2) << std::endl;

    return 0;
}

<fmt/format.h>

Support for {fmt} is available as long as <fmt/format.h> is present. All the above information on modifiers is the same for fmtlib, just in a different namespace (i.e. fmt:: instead of std::).

#include <fmt/format.h>
#include <boost/decimal.hpp> // or <boost/decimal/fmt_format.hpp>
#include <iostream>

int main()
{
    constexpr boost::decimal::decimal64_t val1 {314, -2};
    constexpr boost::decimal::decimal32_t val2 {3141, -3};

    std::cout << fmt::format("{:10.3e}", val1) << '\n';
    std::cout << fmt::format("{:10.3e}", val2) << std::endl;

    return 0;
}