MinGW and setlocale

607 Views Asked by At

I'm trying to set thousand separator to '.' or space and decimal separator to ','.

I'm using gcc.exe (MinGW-W64 x86_64-posix-seh, built by Brecht Sanders) 12.1.0 on Windows 10.

When I try to compile this code:

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

int main(void)
{
    setlocale(LC_ALL, "French");

    int a = 1000000;
    float b = 1.10F;

    printf("%'d.\n", a);
    printf("%'g.\n", b);
    
    return 0;
}

It outputs:

1,000,000.

1,1.

Any idea what’s wrong?

By the way setlocale(LC_ALL, "fr-FR"); does'nt have any effect.

Thank you in advance for your help.

1

There are 1 best solutions below

2
mkulko On

On Windows, using gcc.exe targeting x86_64-w64-mingw32, the code below will output "3,141593". On the gcc.exe compiler targeting x86_64-pc-msys, however, the code will output "3.141593". It seems that Windows actually cares about locales more to me. I think you should switch to using MinGW, or, if that isn't an option, sprintf to a variable and replace the last '.' with ',' and everything except the last ',' with a '.'.

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

#define PI 3.14159265

int main(void)
{
        setlocale(LC_NUMERIC, "French");
        printf("%f\n", PI);
        return EXIT_SUCCESS;
}

EDIT: Sorry, I misunderstood the question. I don't really know about how the thousands separator interacts with the locale - so the only thing I can offer is a function that replaces dots with commas and commas with dots. Note that you will need to convert your number to a string with something like sprintf for it to work.

void to_european_format(char * string)
{
        size_t i = 0;
        while (string[i] != '\0')
        {
                if (string[i] == '.')
                        string[i] = ',';
                else if (string[i] == ',')
                        string[i] = '.';

                i++;
        }

        return;
}