Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::to_string — convert a number to text

std::to_string from <string> returns a number's textual representation as a std::string. This entry covers C++23, including floating-point formatting limitations and the distinction from the newer working draft.

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

Syntax

#include <string>

std::string std::to_string(int val);
std::string std::to_string(unsigned val);
std::string std::to_string(long val);
std::string std::to_string(unsigned long val);
std::string std::to_string(long long val);
std::string std::to_string(unsigned long long val);
std::string std::to_string(float val);
std::string std::to_string(double val);
std::string std::to_string(long double val);

std::to_string(value) creates and returns a std::string containing a number's representation. It requires <string> and does not print anything by itself. Its overloads accept int, unsigned, long, unsigned long, long long, unsigned long long, float, double, and long double. Integers are written in decimal, with a - sign for negative values.

In C++23, conversion behaves like the corresponding sprintf formatting. Finite floating-point values use fixed-point notation with six digits after the decimal separator. The separator depends on the global C locale. Small values can round to zero. In the "C" locale, std::to_string(1e-7) can produce "0.000000" with rounding to nearest. If sprintf honors the active rounding mode, rounding upward can produce "0.000001" instead. Do not treat this function as a lossless representation of arbitrary floating-point numbers.

The function accepts no arguments for choosing a base or precision. You can concatenate the returned text with another std::string, as the example does. This converts a number to text; it does not parse text into a number.

Version scope: this entry targets C++23, matching the repository compiler flag; the production runtime is not attested. The current draft at the supplied addresses already specifies the result as format("{}", val) and records changed floating-point results relative to C++23. Do not apply that newer behavior to C++23.

Examples

#include <iostream>
#include <string>

int main() {
    const std::string message = std::string("count=") + std::to_string(-42);
    std::cout << message << '\n';
}

Result

count=-42

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