Search code examples
c++number-formatting

Format number with commas in C++


I want to write a method that will take an integer and return a std::string of that integer formatted with commas.

Example declaration:

std::string FormatWithCommas(long value);

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"

What is the C++ way of formatting a number as a string with commas?

(Bonus would be to handle doubles as well.)


Solution

  • Use std::locale with std::stringstream

    #include <iomanip>
    #include <locale>
    
    template<class T>
    std::string FormatWithCommas(T value)
    {
        std::stringstream ss;
        ss.imbue(std::locale(""));
        ss << std::fixed << value;
        return ss.str();
    }
    

    Disclaimer: Portability might be an issue and you should probably look at which locale is used when "" is passed