Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::chars_format — floating-point conversion format

std::chars_format selects floating-point notation for std::to_chars and parsing rules for std::from_chars. It provides general, fixed, scientific, and hex formats; it does not set precision by itself.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <charconv>
std::chars_format::general
std::chars_format::fixed
std::chars_format::scientific
std::chars_format::hex

std::chars_format, declared in <charconv>, is a scoped enumeration and bitmask type used by the floating-point overloads of std::to_chars and std::from_chars. The numeric values of scientific, fixed, and hex are unspecified; general equals fixed | scientific. Pass one of the named values to a conversion, not an arbitrary combination of bits.

For output, std::chars_format::fixed selects decimal notation without an exponent, while std::chars_format::scientific selects decimal notation with an exponent. std::chars_format::general chooses between these forms. std::chars_format::hex selects hexadecimal notation with a power-of-two exponent marked by p, without a 0x prefix.

Precision is a separate std::to_chars argument: for fixed and scientific, it specifies digits after the decimal point; for general, it specifies significant-digit precision. Do not interpret it as the number of decimal places for every format. The function does not append a null terminator; check ec and use the range ending at ptr.

For input through std::from_chars, scientific requires an exponent, fixed disallows one, and the default general accepts either form. The hex format does not consume a 0x prefix: given 0x123, it can successfully parse only 0, leaving x123. If the entire input must be consumed, check both ec and ptr == last.

Examples

#include <charconv>
#include <iostream>
#include <system_error>

int main() {
    const std::chars_format formats[] = {
        std::chars_format::fixed,
        std::chars_format::scientific,
        std::chars_format::general
    };

    for (auto fmt : formats) {
        char buffer[64];
        const auto result = std::to_chars(
            buffer, buffer + sizeof buffer, 12.5, fmt, 3);
        if (result.ec != std::errc{}) {
            std::cerr << "conversion failed\n";
            return 1;
        }
        std::cout.write(buffer, result.ptr - buffer);
        std::cout << '\n';
    }
}

Result

12.500
1.250e+01
12.5

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources