整数をコンマ区切りの数値文字列に変換する

整数をコンマ区切りの数値文字列に変換するには、GetNumberFormat関数を使います。例えば、次のようにします。
//---------------------------------------------------------------------------
#include <Utilcls.h>
//---------------------------------------------------------------------------
AnsiString __fastcall FormatInt(int AInt)
{
        return FormatIntString(AInt);
}
//---------------------------------------------------------------------------
AnsiString __fastcall FormatUInt(unsigned int AUInt)
{
        return FormatIntString(AUInt);
}
//---------------------------------------------------------------------------
AnsiString __fastcall FormatInt64(__int64 AInt64)
{
        return FormatIntString(AInt64);
}
//---------------------------------------------------------------------------
AnsiString __fastcall FormatUInt64(unsigned __int64 AInt64)
{
        return FormatIntString(AUInt64);
}
//---------------------------------------------------------------------------
AnsiString __fastcall FormatIntString(AnsiString AIntString)
{
        NUMBERFMT numberFormat = {0};
        numberFormat.NumDigits = 0;
        numberFormat.LeadingZero = 1;
        numberFormat.Grouping = 3;
        numberFormat.lpDecimalSep = ".";
        numberFormat.lpThousandSep = ",";
        numberFormat.NegativeOrder = 1;
        TAPtr<TCHAR> buffer = NULL;
        int bufferSize = 0;
        for(int i = 0; i < 2; i++) {
                ::SetLastError(NO_ERROR);
                int stringLength = GetNumberFormat(
                        LOCALE_USER_DEFAULT,
                        0,
                        AIntString.c_str(),
                        &numberFormat,
                        buffer,
                        bufferSize);
                if(::GetLastError() != NO_ERROR) {
                        return AnsiString();
                }
                if(i == 0) {
                        buffer = new char[stringLength];
                        bufferSize = stringLength;
                }
                else {
                        if(stringLength != bufferSize) {
                                return AnsiString();
                        }
                }
        }
        return AnsiString(buffer);
}
//---------------------------------------------------------------------------
最終更新: 2008-07-05

戻る