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,239 questions

56,142 answers

573 users

How to print a number with a thousand separator as spaces in C

1 Answer

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

/*
    Program: Print numbers with a thousand separator as spaces.

    Architecture notes:
    -------------------
    - C does not provide built-in thousands separators.
    - We implement a manual formatter:
        * Convert the number to a string.
        * Walk from the end toward the beginning.
        * Insert spaces every three digits.
    - Works for positive and negative integers.
    - Uses dynamic memory for the formatted string; caller frees it.

    Performance notes:
    ------------------
    - O(n) time where n is the number of digits.
    - Memory usage is small: at most ~1.33× the original digit count.
    - No external libraries; only standard C.

    Pitfalls:
    ---------
    - Must handle negative numbers carefully (minus sign stays at front).
    - Must ensure enough memory for inserted spaces.
    - Caller must free the returned string.

    Security notes:
    ---------------
    - No external input parsing.
    - Safe for demonstration; avoid printing sensitive values in real systems.

    Tests:
    ------
    - Positive numbers
    - Negative numbers
    - Zero
    - Very large integers (within 64-bit range)
*/


// Format integer with spaces as thousand separators.
// Caller must free the returned string.
char* format_with_spaces(long long value) {
    char buffer[64];  // enough for any 64-bit integer
    snprintf(buffer, sizeof(buffer), "%lld", value);

    size_t len = strlen(buffer);
    int is_negative = (buffer[0] == '-');

    // Count digits excluding minus sign
    size_t digit_count = is_negative ? len - 1 : len;

    // Maximum spaces needed = digit_count / 3
    size_t max_spaces = digit_count / 3;

    // Allocate output buffer
    char* out = malloc(len + max_spaces + 1);
    if (!out) {
        return NULL;
    }

    size_t out_index = 0;
    size_t in_index = 0;

    // Copy minus sign if present
    if (is_negative) {
        out[out_index++] = buffer[in_index++];
    }

    // Number of digits before first group
    size_t first_group = digit_count % 3;
    if (first_group == 0) first_group = 3;

    // Copy first group
    for (size_t i = 0; i < first_group; ++i) {
        out[out_index++] = buffer[in_index++];
    }

    // Copy remaining groups of 3 digits
    size_t remaining = digit_count - first_group;
    while (remaining > 0) {
        out[out_index++] = ' ';
        for (int i = 0; i < 3; ++i) {
            out[out_index++] = buffer[in_index++];
        }
        remaining -= 3;
    }

    out[out_index] = '\0';
    return out;
}


int main(void) {
    long long tests[] = {
        0,
        42,
        1234,
        987654321,
        -1234567,
        1000000000000000000LL
    };

    printf("Running test cases:\n\n");

    for (size_t i = 0; i < sizeof(tests)/sizeof(tests[0]); ++i) {
        char* formatted = format_with_spaces(tests[i]);
        if (!formatted) {
            printf("Memory allocation error\n\n");
            continue;
        }

        printf("Original:  %lld\n", tests[i]);
        printf("Formatted: %s\n\n", formatted);

        free(formatted);
    }

    return 0;
}


/*
run:

Running test cases:

Original:  0
Formatted: 0

Original:  42
Formatted: 42

Original:  1234
Formatted: 1 234

Original:  987654321
Formatted: 987 654 321

Original:  -1234567
Formatted: -1 234 567

Original:  1000000000000000000
Formatted: 1 000 000 000 000 000 000

*/

 



answered 8 hours ago by avibootz
...