I added some extra code to this version in order to check for negative or positive
numbers, and to choose the separator.
Any improvement you can suggest?
Code:
// ----------------------------------------------------------------------------------------------
// Prog_name: comma_sep.c / ver 0.1
// This version takes into account the sign and the possibility to have different
// separator like space, comma, point, and so on.
// Date: 27 june 2010
// Author: frktons @ cprogramming forum.
//-----------------------------------------------------------------------------------------------
// A routine for separating integer numbers with thousands separator.
// Created with Pelles C for Windows 6.00.4
//-----------------------------------------------------------------------------------------------
#include <stdio.h>
#include <stdbool.h>
#undef getchar
#pragma comment(lib, "\\masm32\\lib\\msvcrt.lib")
int main(int argc, char *argv[])
{
bool sign = true; // if the number has to be displayed with sign
bool neg = false; // if the number is negative
bool zero = false;
char sep = ','; // here I choose the separator
int num = -12715; // test number
char buffer[15] = {' '}; // string array for the formatted number
int len_str = 14; // string lenght less the terminator NULL
int x; // generic integer counters
int remain = 0; // integer variable to store the remainder
int count = 0; // integer counter for positioning the separator
char digit[10] = {'0','1','2','3','4','5','6','7','8','9'}; // the digit to display in char shape
printf("\n The value of result is: %d\n",num);
if (num == 0)
{
buffer[len_str] = '0';
zero = true;
goto pgm_end;
}
if (num < 0)
{
neg = true;
num = num * -1 ; // transform number to positive if negative
}
for (x = len_str; x >= 0; x--)
{
if (num == 0)
break;
if (count == 3)
{
count = 0;
buffer[x] = sep;
x--;
}
remain = num % 10;
num = num / 10;
buffer[x] = digit[remain];
count++;
}
pgm_end:
if (sign == true && neg == true)
buffer[x] = '-';
else if (sign == true && zero == false)
buffer[x] = '+';
// end if
printf("\n The formatted value of result is: ");
for (x = 0; x < 15; x++)
{
if (buffer[x] == '+' || buffer[x] == '-' || buffer[x] == sep || buffer[x] >= '0' && buffer[x] <= '9')
printf("%c",buffer[x]);
}
getchar();
return 0;
}
And the output:
Code:
The value of result is: -12715
The formatted value of result is: -12,715
Enjoy