How to convert number to decimal string?
Categories:
Converting Numbers to Decimal Strings in C/C++

Learn various methods to convert integer and floating-point numbers into their decimal string representations in C and C++.
Converting numbers to their string representations is a common task in programming, essential for displaying output, logging, or interacting with text-based interfaces. In C and C++, there are several approaches to achieve this, each with its own advantages and use cases. This article explores the most common and effective methods for both integer and floating-point types.
Understanding the Conversion Process
At its core, converting a number to a decimal string involves transforming its binary representation into a sequence of ASCII or Unicode characters that correspond to its decimal digits. For integers, this typically involves repeatedly dividing by 10 and taking the remainder. For floating-point numbers, the process is more complex, involving handling the integer and fractional parts separately, as well as managing precision and potential scientific notation.
flowchart TD A[Start with Number] --> B{Is Integer?} B -- Yes --> C[Repeatedly Divide by 10] C --> D[Collect Remainders (Digits)] D --> E[Reverse Digits] B -- No --> F[Handle Floating Point] F --> G[Separate Integer & Fractional Parts] G --> H[Convert Integer Part (as above)] G --> I[Convert Fractional Part (multiply by 10, take digit)] H & I --> J[Combine with Decimal Point] E & J --> K[Result: Decimal String] K --> L[End]
Conceptual flow for number to decimal string conversion.
Integer to String Conversion (C-style)
In C, the sprintf
function from <cstdio>
(or <stdio.h>
) is a versatile tool for formatting output, including converting integers to strings. It works similarly to printf
but writes its output to a character array (string buffer) instead of standard output. Another option is itoa
(integer to ASCII), though it's non-standard and less portable.
#include <cstdio> // For sprintf
#include <cstdlib> // For itoa (non-standard)
#include <iostream>
int main() {
int num = 12345;
char buffer[20]; // Buffer to hold the string
// Using sprintf (standard and recommended)
sprintf(buffer, "%d", num);
std::cout << "sprintf result: " << buffer << std::endl;
// Using itoa (non-standard, but common on Windows)
// _itoa_s(num, buffer, 10); // Safer version for Windows
// itoa(num, buffer, 10); // Standard itoa
// std::cout << "itoa result: " << buffer << std::endl;
return 0;
}
Integer to string conversion using sprintf
in C.
sprintf
, always ensure your buffer is large enough to prevent buffer overflows, which can lead to security vulnerabilities. Consider using safer alternatives like snprintf
in C or C++ streams.Integer to String Conversion (C++ Standard Library)
C++ offers more type-safe and convenient ways to convert numbers to strings, primarily through std::to_string
(C++11 and later) and string streams (std::stringstream
). These methods avoid manual buffer management and integrate well with the C++ Standard Library.
#include <string>
#include <iostream>
#include <sstream> // For std::stringstream
int main() {
int num = -67890;
// Using std::to_string (C++11 and later)
std::string s1 = std::to_string(num);
std::cout << "std::to_string result: " << s1 << std::endl;
// Using std::stringstream
std::stringstream ss;
ss << num;
std::string s2 = ss.str();
std::cout << "std::stringstream result: " << s2 << std::endl;
return 0;
}
Integer to string conversion using std::to_string
and std::stringstream
in C++.
Floating-Point to String Conversion
Converting floating-point numbers (like float
or double
) to strings requires careful handling of precision and formatting. sprintf
and std::stringstream
are the primary tools for this, allowing control over the number of decimal places, scientific notation, and other formatting options.
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip> // For std::fixed, std::setprecision
int main() {
double pi = 3.1415926535;
char buffer[50];
// Using sprintf for floating-point (C-style)
sprintf(buffer, "%.4f", pi); // 4 decimal places
std::cout << "sprintf (4 decimal places): " << buffer << std::endl;
sprintf(buffer, "%g", pi); // General format, removes trailing zeros
std::cout << "sprintf (general format): " << buffer << std::endl;
// Using std::stringstream for floating-point (C++-style)
std::stringstream ss;
ss << std::fixed << std::setprecision(6) << pi; // 6 decimal places
std::string s1 = ss.str();
std::cout << "stringstream (6 decimal places): " << s1 << std::endl;
std::stringstream ss2;
ss2 << pi; // Default precision
std::string s2 = ss2.str();
std::cout << "stringstream (default precision): " << s2 << std::endl;
// Using std::to_string (less control over precision)
std::string s3 = std::to_string(pi);
std::cout << "std::to_string (floating point): " << s3 << std::endl;
return 0;
}
Floating-point to string conversion with precision control.
std::stringstream
combined with manipulators like std::fixed
, std::scientific
, and std::setprecision
from <iomanip>
is generally preferred in C++ over sprintf
.Performance Considerations
While std::to_string
and std::stringstream
are convenient and safe, sprintf
can sometimes offer better performance, especially in performance-critical applications or when dealing with very large numbers of conversions. However, the performance difference is often negligible for typical use cases, and the safety and ease of use of C++ standard library functions usually outweigh the minor performance gain of sprintf
.
graph TD A[Performance] A --> B{Conversion Method} B --> C[sprintf] B --> D[std::stringstream] B --> E[std::to_string] C -- Generally Faster --> F[Manual Buffer Management] D -- Safe & Flexible --> G[Automatic Buffer Management] E -- Simple & Convenient --> G F --> H[Risk of Buffer Overflow] G --> I[Higher Overhead (sometimes)]
Performance and safety trade-offs of different conversion methods.
Practical Steps for Conversion
Here's a summary of practical steps to convert numbers to decimal strings based on your C/C++ environment and requirements.
1. Choose Your Method
For C++11 or newer, std::to_string
is the simplest for basic integer/float conversion. For more control over formatting (especially floating-point precision), std::stringstream
is the C++ idiomatic choice. In C, or for C-style string manipulation, sprintf
is the standard.
2. Include Necessary Headers
For sprintf
, include <cstdio>
. For std::to_string
, include <string>
. For std::stringstream
and formatting manipulators, include <sstream>
and <iomanip>
respectively.
3. Perform the Conversion
Use the chosen function or object to convert your number. Remember to provide a sufficiently sized character array for sprintf
or let std::string
handle memory for C++ methods.
4. Handle Output and Error Checking
Display the resulting string or use it as needed. For sprintf
, check the return value to ensure the conversion was successful and didn't truncate the output. C++ methods generally throw exceptions on allocation failure, which can be caught.