skip to Main Content

How to format a thousand separator in C with FreeBSD? I obtain the code from one of the answers here How can I format currency with commas in C? and it is working in my Ubuntu Linux system but not in my FreeBSD 11.4 and 14-CURRENT systems.

#include <stdio.h>
#include <locale.h>

int main(void)
{
    setlocale(LC_NUMERIC, "");
    printf("$%'.2Lfn", 123456789.00L);
    printf("$%'.2Lfn", 1234.56L);
    printf("$%'.2Lfn", 123.45L);
    return 0;
}

2

Answers


  1. Chosen as BEST ANSWER

    Just found this, by specifying this argument en_US.UTF-8 in the setlocale() will also provide thousand separator in C with FreeBSD.

    #include <stdio.h>
    #include <locale.h>
    
    int main(void)
    {
        setlocale(LC_NUMERIC, "en_US.UTF-8");
        printf("$%'.2Lfn", 123456789.00L);
        printf("$%'.2Lfn", 1234.56L);
        printf("$%'.2Lfn", 123.45L);
        return 0;
    }
    

  2. The printf manpage(3) says:

    `” (apostrophe) Decimal conversions (d, u, or i) or the integral
    portion of a floating point conversion (f or F) should be grouped and
    separated by thousands using the non-monetary separator returned by
    localeconv(3).

    so, it uses the locale separator.

    You can do something like that:

    #include <stdio.h>
    #include <locale.h>
    
    int main(void)
    {
        const char sep = ''';
    
        setlocale(LC_NUMERIC, ""); 
        localeconv()->thousands_sep[0] = sep;
    
        printf("$%'04.2Lfn", 123456789.00L);
        printf("$%'04.2Lfn", 1234.56L);
        printf("$%'04.2Lfn", 123.45L);
    
        return 0;
    }
    

    then compile like this:

    cc -o myprog myprog.c
    

    which will output:

    ./myprog
    $123'456'789.00
    $1'234.56
    $123.45
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search