Software Bpath Network


Numbers And Localization


Language: C++
Compiler: MS Visual C++ 5.0 SP3
Environment: Windows 9x/NT

What's this?


This is a method allows you to print numbers with the format you specify in Control Panel - International Settings - Numbers.

How does it work?


This represents the common way to print numbers, date and currency using the Control Panel format:

    #include <locale.h>
    ...
    ...
    ...
    setlocale(LC_ALL, ".OCP");

But this is not enough for numbers!
If you really want to convert a number to a string containing that number in the format you specify in Control Panel, you have to use this function:

CString Number2String(long double nNumber, int nDecimals)
{
    CString sBuffer, sFormat, sRet;
    NUMBERFMT nf;
    int nRet, nDecimalPos, MAX_CHARS = 128;
    char sDest[128], sDummy[16], sDecSep[16], sThowSep[16];
    
    nf.NumDigits = nDecimals;
    GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_ILZERO, sDummy, 16 );
    nf.LeadingZero = atoi(sDummy);
    GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_SGROUPING, sDummy, 16 );
    nf.Grouping = atoi(sDummy);
    GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_SDECIMAL, sDecSep, 16 );
    nf.lpDecimalSep = sDecSep;
    GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_STHOUSAND, sThowSep, 16 );
    nf.lpThousandSep = sThowSep;
    GetLocaleInfo( LOCALE_SYSTEM_DEFAULT, LOCALE_INEGNUMBER, sDummy, 16 );
    nf.NegativeOrder = atoi(sDummy);
    
    sFormat.Format("%%.%df", nDecimals );
    sBuffer.Format( sFormat, nNumber);
    // sBuffer must contain the number in standard (English) format
    nDecimalPos = sBuffer.Find( localeconv()->decimal_point );
    if( nDecimalPos != -1 )
        sBuffer.SetAt(nDecimalPos, '.' );
    // ready to convert...
    nRet = GetNumberFormat(LOCALE_SYSTEM_DEFAULT, 0, sBuffer, &nf, sDest, MAX_CHARS);
    if( nRet )
        sRet = sDest;
    else
        sRet = "";
    return sRet;
}

Call this function passing the number you want to convert and the decimals you want to display and receive the string you need.
That's all!

Now you can send me a comment or suggestions for next atricles. Thanks.
Feel free to contact me if you found an error (any kind) in this article.


Back to Articles Page