Search code examples
cfor-loopnumber-formatting

Inserting commas in numbers using for loop not working


I tried making a program where it will put a comma in a certain place between numbers. My explanation may be is vague, but I just wanted to make 12345678.23 into 12,345,678.23. I hope that cleared my explanation tho. Here is my code.

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

void main()
{
  char m[20]="12345678.23";
    int j=11, a, t=1, r=4, s;
    
    
        for(a=0; a=11; a++)
        {
            if(strlen(m)==j)
            {printf("%c", m[a]);
            if(a==t)
            {printf(",");}
            if(a==r)
            {printf(",");}
            }   
        }
        
    
}

This program doesn't work and I don't know why. I hope you guys can help me. Thank you very much!


Solution

  • #include <stdio.h>
    #include <string.h>
    
    int main(void) // Use the proper signature
    {
        char m[] = "123"; // Do not hardcode the size
        char *p; // A pointer to traverse the string
        int mod; // Useful to know when to insert a comma
    
        p = strchr(m, '.'); // Position of the decimal separator
        if (p == NULL)
        {
            p = strchr(m, '\0'); // Don't have decimal separator
        }
        mod = (p - m) % 3; // Comma must be placed on each mod count
        p = m; // Rewind the pointer
        while (*p != '\0') // While the character is not NUL
        {
            if (*p == '.') // Decimal separator reached
            {
                mod = 3; // Avoid divisibility
            }
            // If position divisbile by 3 but not the first pos
            if ((p != m) && (mod != 3) && (((p - m) % 3) == mod))
            {
                putchar(',');
            }
            putchar(*p);
            p++; // Next character
        }
        putchar('\n');
        return 0;    
    }
    

    Output:

    12,345,678.23