c++: Format number with commas?

User picture User · Sep 1, 2011 · Viewed 73.8k times · Source

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 result = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);
// result = "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.)

Answer

Jacob picture Jacob · Sep 1, 2011

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