Need to print numbers formatted with commas

In my program I need the output to have commas for numbers greater than 999. How can I do this? Thanks!

if (ticket_price == 250)
cout << "The total sales for Box seats were: $" << ticket_cnt * ticket_price << endl;
Last edited on
This is the canonical C++ way to specify rules for punctuation of numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <iomanip>
#include <locale>
#include <string>

int main()
{
    // see: http://en.cppreference.com/w/cpp/locale/numpunct/grouping
    struct with_commas : std::numpunct<char>
    {
        protected:

           // group every three digits before the decimal point
           virtual std::string do_grouping() const override { return "\3"; }

           // use ',' as the group seperator
           virtual char do_thousands_sep() const override { return ',' ; }
    };

    // see: http://en.cppreference.com/w/cpp/io/basic_ios/imbue
    // http://en.cppreference.com/w/cpp/locale/locale/locale overload (7)
    // the locale calls delete on the facet when it is destroyed.
    auto original_locale = std::cout.imbue( std::locale( std::cout.getloc(), new with_commas ) );

    const double ticket_price = 123.45 ;
    const int ticket_cnt = 26173 ;

    std::cout << "The total sales for Box seats were: $ " << std::fixed
               << std::setprecision(2) << ticket_cnt * ticket_price << '\n' ;

    // std::cout.imbue(original_locale) ;
    // ...
}

http://coliru.stacked-crooked.com/a/98d818cd1aba0627

If this would be deemed unacceptable, you would need to use modulo division by 1000 to get the remainder etc. If you are working with floating point numbers, see: http://en.cppreference.com/w/cpp/numeric/math/fmod
Topic archived. No new replies allowed.