Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

How to print an integer with comma separator in C

1 Answer

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

void formatNumberWithCommas(int n, char *output) {
    char temp[64]; // Temporary buffer
    sprintf(temp, "%ld", n); // Convert the number to a string

    int length = strlen(temp);
    int commas = (length - 1) / 3; // Calculate the number of commas
    char *p = &temp[length]; // Pointer to the end of the number string
    char *commasp = output + length + commas; // Pointer to the end of the output buffer

    *commasp-- = *p--; // Null-terminate the output string
    for (int i = 1; p >= temp; i++) {
        *commasp-- = *p--; // Copy digits
        if ((i % 3) == 0 && p >= temp) {
            *commasp-- = ','; // Insert commas
        }
    }
}

int main(void) {
    int n = 83907652;
    char commas_number[64];

    formatNumberWithCommas(n, commas_number);

    puts(commas_number);

    return 0;
}

 
/*
run:
 
83,907,652
 
*/

 



answered Mar 29, 2025 by avibootz
...