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 (constunsignedlonglong 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;
}
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.