Skip to content
C++: Parse a complete finite decimal value

C++: Parse a complete finite decimal value

November 11, 2026

A timeout setting such as 1.5seconds must not silently become 1.5. A floating-point parser can accept a valid prefix, so a configuration reader needs to check where parsing stopped. It also needs a policy for infinity and NaN.

Prepare a scratch directory

Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save as cpp-parse-finite-decimal-values.cpp:

#include <cassert>
#include <charconv>
#include <cmath>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>

std::optional<double> parse_decimal(std::string_view text) {
    if (text.empty()) return std::nullopt;
    double value = 0;
    const auto result = std::from_chars(
        text.data(), text.data() + text.size(), value,
        std::chars_format::general);
    if (result.ec != std::errc{} ||
        result.ptr != text.data() + text.size() || !std::isfinite(value)) {
        return std::nullopt;
    }
    return value;
}

int main() {
    assert(parse_decimal("1.25") == 1.25);
    assert(parse_decimal("-2e1") == -20.0);
    assert(!parse_decimal(""));
    for (std::string_view text : {"1.25", "-2e1", "1.5seconds", " 1.5",
                                 "+1.5", "nan", "inf", "1e9999"}) {
        const auto value = parse_decimal(text);
        std::cout << text << ": ";
        if (value) std::cout << *value << '\n';
        else std::cout << "rejected\n";
    }
}

Compile and run:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-parse-finite-decimal-values.cpp -o cpp-parse-finite-decimal-values &&
./cpp-parse-finite-decimal-values

Observed output:

1.25: 1.25
-2e1: -20
1.5seconds: rejected
 1.5: rejected
+1.5: rejected
nan: rejected
inf: rejected
1e9999: rejected

How it works

from_chars reports conversion errors through ec and the first unconsumed character through ptr. Requiring both success and the end pointer rejects suffixes. The explicit empty-input check also avoids forming an end pointer from an empty view with a null data pointer.

This parser rejects leading whitespace and a leading plus sign. Signs in the exponent are allowed, as is a minus sign before the value. Floating-point conversion may accept infinity and NaN spellings, so std::isfinite supplies a separate application rule.

Limits and choices

Finite does not mean positive, in range for a timeout, or exactly representable. Apply the setting’s bounds after parsing, before converting to another numeric type. Decimal fractions usually round to a nearby binary value. This example accepts an existing string view and does not limit how much input the caller reads. It requires a standard library with floating-point from_chars support; testing an integer overload alone does not establish that support.

The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.

Clean up

rm -- cpp-parse-finite-decimal-values.cpp cpp-parse-finite-decimal-values
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining files before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on