Home > Article > Backend Development > How to Format Numbers with Commas in C Using std::locale?
Formatting Numbers with Commas in C
In C , the std::locale class provides a locale-dependent way to format numbers with commas.
std::locale with std::stringstream
To format a number as a string with commas, you can use std::locale with std::stringstream as follows:
<code class="cpp">#include <iomanip> #include <locale> template<class T> std::string FormatWithCommas(const T& value) { std::stringstream ss; ss.imbue(std::locale("")); // Use the system's locale ss << std::fixed << value; return ss.str(); }</code>
Example Usage:
<code class="cpp">std::string result1 = FormatWithCommas(7800); std::string result2 = FormatWithCommas(5100100); std::string result3 = FormatWithCommas(201234567890); // result1 = "7,800" // result2 = "5,100,100" // result3 = "201,234,567,890"</code>
Handling Doubles
To format a double as a string with commas, you can use the same approach as above, but the code will need to handle the decimal point:
<code class="cpp">template<class T> std::string FormatWithCommas(const T& value) { std::stringstream ss; ss.imbue(std::locale("")); ss << std::fixed << std::setprecision(2) << value; return ss.str(); }</code>
Disclaimer:
Note that the portability of the above solutions might be an issue, as the locale used when "" is passed may vary depending on the system.
The above is the detailed content of How to Format Numbers with Commas in C Using std::locale?. For more information, please follow other related articles on the PHP Chinese website!