How to print number with thousands separator in C

2 Answers

0 votes
#include <stdio.h>

void printnumberswiththousandsseparator(int n);
void printnumberswiththousandsseparatorcomma(int n);

int main()
{
    printnumberswiththousandsseparator(199); printf("\n");
    printnumberswiththousandsseparator(1234); printf("\n");
    printnumberswiththousandsseparator(190008600); printf("\n");
    printnumberswiththousandsseparator(-10000000); printf("\n");

    return(0);
}
void printnumberswiththousandsseparatorcomma(int n)
{
    if (n < 1000) {
        printf("%d", n);
        return;
    }
    printnumberswiththousandsseparatorcomma(n / 1000);
    printf(",%03d", n % 1000);
}
void printnumberswiththousandsseparator(int n)
{
    if (n < 0) {
        printf("-");
        n = -n;
    }
    printnumberswiththousandsseparatorcomma(n);
}



/*
run:

199
1,234
190,008,600
-10,000,000

*/

 



answered Jun 8, 2015 by avibootz
edited Dec 11, 2024 by avibootz
0 votes
#include <stdio.h>
#include <locale.h>

int main() {
    long double ld = 98153056842;

    setlocale(LC_NUMERIC, "");
    printf("%'.2Lf\n", ld);

    int n = -84971642;
    printf("%'d\n", n);

    return 0;
}



/*
run:

98,153,056,842.00
-84,971,642

*/

 



answered Dec 11, 2024 by avibootz

Related questions

1 answer 212 views
1 answer 198 views
1 answer 231 views
1 answer 166 views
1 answer 221 views
1 answer 127 views
1 answer 138 views
...