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:
#include
#include
template
std::string FormatWithCommas(const T& value) {
std::stringstream ss;
ss.imbue(std::locale("")); // Use the system's locale
ss Example Usage:
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"
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:
template
std::string FormatWithCommas(const T& value) {
std::stringstream ss;
ss.imbue(std::locale(""));
ss 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3