add a comma to long numbers?

how can I add a comma every 3 decimal places to a long number of int type?
Do you mean when printing it out to a stream? Use the appropriate locale, e.g.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <locale>
int main()
{
    // American locale happens to use commas every 4 decimal places
    // on Linux and many other OSes, it's called "en_US"
    std::cout.imbue(std::locale("en_US.utf8"));
    std::cout << 123456789 << '\n';
}

demo: http://ideone.com/2Mgbno

If you happen to use an OS that doesn't provide localization support, you can do it yourself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <locale>

struct threes : std::numpunct<char>
{
    std::string do_grouping() const { return "\3"; }
    // note: comma is provided by std::numpunct<char>
};

int main()
{
    std::cout.imbue(std::locale(std::cout.getloc(), new threes));
    std::cout << 123456789 << '\n';
}

demo: http://ideone.com/ofwymf
Last edited on
The brute force method:

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
34
#include <iostream>

// works for integer types
void print_with_commas( unsigned long long n )
{
    const unsigned int THOUSAND = 1000 ;

    if( n < THOUSAND )
    {
        std::cout << n ;
    }
    else
    {
        int remainder = n % THOUSAND ;
        print_with_commas( n / THOUSAND ) ;
        std::cout << ',' << remainder ;
    }
}

int main()
{
    const int n = 123456789 ;
    print_with_commas(n) ; // 123,456,789
    std::cout << '\n' ;

    int m = -1234567 ;
    if( m < 0 )
    {
        std::cout << '-' ;
        m = -m ;
    }
    print_with_commas(m) ; // -1,234,567
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/a3a75f88a478c0d3
Last edited on
Topic archived. No new replies allowed.