My program contains some very large integers and uses the GMP library. The output contains integers (probably small enough to fit into int
). I would like to make the output easy to read by adding commas between every three digits with any left overs on the left side.
Examples:
1234 => 1,234
12345 => 12,345
123456 => 123,456
123 => 123
The input of the function would be a string
representing an integer, because the value of the mpz_class
would be converted to a string. I know there's been a lot of discussion of adding commas to int
but not string
. The mpz_class
can't be converted to an int
because it may be too big.
Here is what I have and it isn't pretty.
using namespace std;
/*add commas between groups of 3 digits with remainder on left side*/
string addCommas(string in)
{
const int length = in.length();
if(length < 4)
{
return in;
}
int inserted = 0;
int i = length % 3;
if(i == 0)
{
i = 3;
}
for(; i < length + inserted; i = i + 4)
{
in.insert(i, ",");
inserted++;
}
return in;
}
Given its use in the program, it is guaranteed the input will not be a negative number. Though I still wonder if it's good to include a check? The program focuses on quick results. How can this code be more readable?
string
type. Is it very similar tostd::string
(if so, why not usestd::string
?) \$\endgroup\$using namespace std;
\$\endgroup\$