Re: Using CRT functions to convert string to double
Markus E?mayr schrieb:
Hello,
I have a very simple thing to do, but I can't get it to work.
I'm located in Austria where numbers (especially amounts) are formatted like
this:
123.456,78
You see, the period is the grouping character, the colon is the decimal
separator.
My application now has to convert any string containing such a number to a
double, to be able to compare it and calculate with.
I have asked myself the same question for some time...
For the conversion from a simple number string to a string formated for
a locale you can use the GetNumberFormat API function. But I did not yet
find the counterpart that scans the string and converts it into a double.
However, I realized that the COM conversion functions seem to honour
locale information. You could try something like this:
CComVariant num(_T("123.456,78"));
if (SUCCEEDED(num.ChangeType(VT_R8))
{
double number = num.dblVal;
}
but I have no idea if that works.
Norbert
So, my first attempt was just to use the atof function.
But that gave me 123.456 as result (i used the period here as decimal
separator).
I now also tried to use strtod and sscanf, but the result was always the
same.
The I used GetThreadLocale to get the current threads locale, converted it
to a _locale_t using a function I found in the web
(http://www.eggheadcafe.com/software/aspnet/29500423/convert-lcid-to-localet.aspx)
and tried to use the functions _atof_l, _strtod_l, _sscanf_l.
But then I always got 123 as a result, even the _locale_t structure
contained the correct values for the formatting characters (period for
grouping, colon for decimal places).
Now, I really don't know what I should try next!?!?
Are the *_l functions behaving incorrectly?
System environment:
Microsoft Windows XP (Service Pack 2 + Hotfixes) (English)
German MUI installed
Region settings are German (Austria)
Microsoft Visual Studio 2005
Please help!
Thanks very much!
Max