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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple formatting question

Status
Not open for further replies.

gonzilla

Programmer
Apr 10, 2001
125
US
Hi,

I'm new to C. All I was wondering is if there was a simple way to format output with the printf() function to have a long number (floats or ints) use commas...

1000000.00 is instead printed 1,000,000.00

I'm thinking it may involve using strings or an array of the number and print a "," for every third index. What is the easiest way? Are there alternative ways?

Thanks for your help in advance.

-Tyler
 
How about brute force,

for a positive int:

#include <stdio.h>
#include <string.h>

typedef int bool ;

void printInt(int posInt) {
char intStr[12] ; /* holding buff for non-comma result */
int len ; /* length of the non-comma result */
int i ;

sprintf(intStr, &quot;%d&quot;, posInt) ;
len = strlen(intStr) ;
for (i = 0 ; i < len ; i++) {
int place ; /* current place N -- 1 */
bool onesPosition ; /* Test for end condition */
bool nextIsGroupOfThree ; /* is next char div by 3 */

place = len - i ;
putchar(intStr) ;

onesPosition = (place == 1) ; /* prevent &quot;123,456,&quot; */
nextIsGroupOfThree = (place % 3 == 1) ;

if (nextIsGroupOfThree && !onesPosition) {
putchar(',') ;
}
}
return ;
}

This should get you started. It can be easily extended for floats and negatives.

Hope this helps.

Brudnakm
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top