C++ std::to_string() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::to_string

Definition

In C++, std::to_string() converts a numeric value into a std::string.

Include <string>.

This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::to_string(...).

Syntax

Pass any supported numeric type.

C++
std::string a = std::to_string(42);
std::string b = std::to_string(3.5);
CallWhat it does
std::to_string(i)Integer to decimal string.
std::to_string(d)Floating value to string (default format).

Floating formatting uses a default precision—not full control like ostringstream or format.

Library declarations
C++
string to_string(int val);
string to_string(long val);
string to_string(double val);
// ... other numeric overloads

Parameters

ParameterDescription
valueNumeric value to convert.

Return Value

Return ValueDescription
stringDecimal text representation.

C++ Examples

Example 1 — Basic to_string()

Convert an int.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = std::to_string(42);
    std::cout << s << '\\n';
    return 0;
}

How It Works

  1. Integer 42 is converted.
  2. Result is a std::string.
  3. Printing shows digits.

Example 2 — Build a Message

Combine label and number.

C++
#include <iostream>
#include <string>

int main() {
    int n = 7;
    std::string msg = "count=" + std::to_string(n);
    std::cout << msg << '\\n';
    return 0;
}

How It Works

  1. to_string makes "7".
  2. String concatenation builds the message.
  3. Output is count=7.

Example 3 — Floating to_string

Convert a double.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = std::to_string(1.5);
    std::cout << s << '\\n';
    return 0;
}

How It Works

  1. Double converts with a default format.
  2. You may see trailing zeros.
  3. Use format/streams for tighter control.

Frequently Asked Questions

Converts numbers to std::string.
Overloads cover common signed and unsigned integer types plus floating types.
to_wstring.
Use std::format or ostringstream.
<string>.

Next: to_wstring()

Keep going through the string functions. Convert a number to std::wstring.

to_wstring() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful