Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: Format number with commas?

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.)

like image 692
User Avatar asked Sep 01 '11 21:09

User


People also ask

How do you put a comma in money?

What are the rules for using commas? First comma is placed three digits from the right of the number to form thousands, second comma is placed next two digits from the right of the number, to mark lakhs and third comma is placed after another next two digits from the right to mark crore, in Indian system of numeration.


2 Answers

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

like image 140
Jacob Avatar answered Sep 26 '22 01:09

Jacob


You can do as Jacob suggested, and imbue with the "" locale - but this will use the system default, which does not guarantee that you get the comma. If you want to force the comma (regardless of the systems default locale settings) you can do so by providing your own numpunct facet. For example:

#include <locale> #include <iostream> #include <iomanip>  class comma_numpunct : public std::numpunct<char> {   protected:     virtual char do_thousands_sep() const     {         return ',';     }      virtual std::string do_grouping() const     {         return "\03";     } };  int main() {     // this creates a new locale based on the current application default     // (which is either the one given on startup, but can be overriden with     // std::locale::global) - then extends it with an extra facet that      // controls numeric output.     std::locale comma_locale(std::locale(), new comma_numpunct());      // tell cout to use our new locale.     std::cout.imbue(comma_locale);      std::cout << std::setprecision(2) << std::fixed << 1000000.1234; } 
like image 36
Node Avatar answered Sep 22 '22 01:09

Node