搜索此博客

2013年4月11日星期四

Output an Integer with Comma Every 3 Digits


Output an integer with comma, for example 1234567, will be "1,234,567"


01 void convert_number(char *str, char *out)
02 {
03         long number = atol(str);
04         if(number < 1000){
05                 strcpy(out, str);
06                 return;
07         }
08 
09 
10         long x = number;
11         long y = 1;
12 
13         while (x > 1000)
14         {
15                 y = y * 1000;
16                 x = x / 1000;
17         }
18 
19         char tmp[4];
20         x = number;
21         while (x > 1000)
22         {
23                 int value = x / y;
24 
25                 if (value < 10 && x != number)
26                         sprintf(tmp, "00%d", value);
27                 else if (value < 100 && x != number)
28                         sprintf(tmp, "0%d", value);
29                 else
30                         sprintf(tmp, "%d", value);
31                 strcat(out, tmp);
32                 strcat(out, ",");
33                 x = x % y;
34                 y = y / 1000;
35         }
36 
37         sprintf(tmp, "%ld", x);
38         strcat(out, tmp);
39 }