Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting Commas into Long

Status
Not open for further replies.

DerPflug

Programmer
Joined
Mar 28, 2002
Messages
153
Location
US
How can I input a long and output a string that is a representation of the long with commas in the correct places?

Example:
Input: 1234567

Output: 1,234,567

Thanks for any help you can offer.
 
First, to make your life easier, always work with the absolute value of the number. This will make your life easier, and then you can put on the negative sign later, as necessary.

Steps:

A. Use sprintf to print the number as a decimal into a text buffer.

B. Count the number of digits. If <= 3, you are done.

C. Calculate the modulus of the count of digits and 3. Something like this:

Code:
p = strlen(szBuf) % 3;

D. If that result is 0... change it to 3.

E. The value you obtained will tell you how many digits to copy before the first comma. From there, you just copy three digits at a time from the first text buffer to another text buffer, then insert a comma.

Example:
(A) Number = 11614127
(B) Number of digits = 8
(C) 8 % 3 = 2;
(D) Okay
(E) That means, copy 2 digits &quot;11&quot;. Then copy a comma, then 3 digits &quot;614&quot; then another comma, then 3 more digits &quot;127&quot;.

I'll leave the coding up to you, but thisis the method I'd use.

I REALLY hope that helps.
Will
 
Try this out:

bool neg = false;
char buffer [20], // the editing buffer.
*pt = &buf[19];
long x; // The number to be edited.
int count = 0; // digit counter
*pt = 0; // terminate the string.
if (x < 0) {
neg = true;
x = -x;
}
if (x == 0) // handle a special case!!
*--pt = '0';
else {
while (x > 0) {
*--pt = x % 10 + '0'; // next digit
if (++count % 3 == 0)
*--pt = ','; // time for a ,
x /= 10;
}
}
if (neg) *--pt = '-';
printf (&quot;%s\n&quot;, pt); // all done.

If it doesn't work precisely right when you compile it, consider it a clever test of your debugging abilities!
 
*********************************************************************
You can also do it this way:
Code:
#include <stdio.h>
#include <string.h>

void main()
{
	long num = 1234567;
	char buff[20] = {0};
	char tmp[20] = {0};

	sprintf( buff, &quot;%ld&quot;, num );
	int len = strlen(buff);

	if( len <= 3 )
	{
		printf(&quot;%d&quot;, num );
		return;
	}

	int rem = len % 3;
	int j = 0;

	for( int i = 0; i < len; i++ )
	{
		if((i != 0) && ( (i == rem) || !( ( i - rem )  % 3) ) )
		{
			tmp[j] = ',';
			j++;
		}

		tmp[j] = buff[i];

		j++;
	}

	printf(&quot;%s&quot;, tmp );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top