Float to std :: string conversion and localization

Can the current locale be changed from float to std :: string?

I am wondering if the above code can generate the result as “1234.5678” instead of “1234.5678” under German, for example:

std::string MyClass::doubleToString(double value) const
{
    char fmtbuf[256], buf[256];
    snprintf(fmtbuf, sizeof(fmtbuf)-1, "%s", getDoubleFormat().c_str());
    fmtbuf[sizeof(fmtbuf)-1] = 0;
    snprintf(buf, sizeof(buf)-1, fmtbuf, value);
    buf[sizeof(buf)-1] = 0;

    return std::string(buf);
}

static std::string const& getDoubleFormat() { return "%f"; }

If so, how can this be prevented? How to always get the output in the form: "1234.5678" with a dot to separate decimal places?

+4
source share
1 answer

<locale> localization of the standard C library affects formatted I / O operations with its character conversion rules and decimal point symbol set in the numeric formatting settings.

// On program startup, the locale selected is the "C" standard locale, (equivalent to english). 
printf("Locale is: %s\n", setlocale(LC_ALL, NULL));
cout << doubleToString(3.14)<<endl;
// Switch to system specific locale 
setlocale(LC_ALL, "");  // depends on your environment settings. 
printf("Locale is: %s\n", setlocale(LC_ALL, NULL));
cout << doubleToString(3.14) << endl;
printf("Locale is: %c\n", localeconv()->thousands_sep);
printf("Decimal separator is: %s\n", localeconv()->decimal_point); // get the point 

Result:

Locale is: C
3.140000
Locale is: French_France.1252
3,140000
Decimal separator is: ,

++, ++ <locale>, . , , C ++:

cout << 3.14<<" "<<endl;   // it still the "C" local 
cout.imbue(locale(""));    // you can set the locale only for one stream if desired
cout << 3.14 << " "<<1000000<< endl; // localized output

:

:

static std::string const& getDoubleFormat() { return "%f"; }

. , "%f", const char[3]. , , string const char* . , !

.

+1

All Articles