Big number. Add commas to them if more than 4 digits

My code here works, but it gives a comma to a 4-digit number, e.g. 5890 become 5,890. But I actually don't want that. But if I change the <= 3 condition to <= 4, the number 1000000000 becomes 1000,000,000 instead of 1,000,000,000. So how do I get what I want (without writing if(number of digits > 4) every time I want to use this function)? The function is used recursively here, so I cannot put a boolean flag to indicate whether to use the <= condition or not because the boolean value won't be remembered.
1
2
3
4
5
6
7
8
string bigNumberWithCommas (const unsigned long long n) {
	string numStr = intstr (n), group;  // I wrote intstr (int to string myself)
	if (numStr.length () <= 3)
		return numStr;
	group = numStr.substr (numStr.length () - 3, 3);
	numStr.resize (numStr.length () - 3);
	return bigNumberWithCommas (atoi (numStr.c_str ())) + "," + group;  
}
Last edited on
But I actually don't want that.


I haven't looked at your code but if you don't want 4 digit numbers to have a comma, and larger numbers to use the comma, then add a condition, such as:
if (x <= 9999)
// don't use a comma
else
// use a comma
One way to accomplish what you want is to call the code with a wrapper that always does the initial check for you. Another way would be to rewrite the function. It isn't really a great candidate for recursion anyway, especially the way you're doing it where you convert to and from a string twice per invocation of the function.

Here's a simple iterative version:

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
template <typename T>
std::string num_to_str(T t)
{
    std::ostringstream os;
    os << t;
    return os.str();
}

std::string bigNumberWithCommas(unsigned long long n)
{
    std::string str = num_to_str(n); // C++11:  str = std::to_string(n) ;

    if (str.length() < 5)
        return str;

    // position of the first comma to insert:
    std::size_t pos = str.length() % 3;
    if (pos == 0)
        pos = 3;

    while (pos < str.length())
    {
        str.insert(pos, 1, ',');
        pos += 4; // skip the comma plus 3 digits.
    }

    return str;
}
Just to show a way to insert those commas using the standard library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <sstream>
#include <locale>
#include <climits>

struct my_nump : std::numpunct<char> {
    std::string do_grouping() const { return "\3"; }
};

std::string bigNumberWithCommas(unsigned long long n) {
    std::ostringstream s;
    if(n > 9999)
        s.imbue(std::locale(s.getloc(), new my_nump));
    s << n;
    return s.str();
}

int main()
{
    std::cout << bigNumberWithCommas(LLONG_MAX) << '\n'
              << bigNumberWithCommas(1234) << '\n';
}


live demo online: http://ideone.com/gZY4XQ
Topic archived. No new replies allowed.