Search code examples
c++builderansistring

AnsiString to Double C++


I am trying to convert an AnsiString to a double, but after running the programm, it says "20.60 is not a valid floating point".

AnsiString Temperatur

RE_Temperatur->Text = Temperatur;

Chart1->Series[0]->AddXY(DT_Uhrzeit->Time, RE_Temperatur->Text.ToDouble(), 
"", clRed);

The value for Temperatur comes from a SerialPort connection from my Arduino and delivers something like 20.60 and so on. When I cut the string to the first 2 digits it is working fine. Guess the . has something to do with the error but I dont know how to solve it.

EDIT // I now tried to just replace the "." with a "," with following code:

    RE_Temperatur->Text = StringReplace(RE_Temperatur->Text, ".", ",", 
    TReplaceFlags() << rfReplaceAll);

Now I get an Error Message "20,60 is not a valid floating point". Its so frustrating :/


Solution

  • Try this simple piece of code in a new console program:

    AnsiString Temperatur = "12.45"; // locale independent
    AnsiString Temperatur2 = "12,45"; // correct in my German locale
    
    double temp = StrToFloat(Temperatur, TFormatSettings::Invariant());
    double temp2 = StrToFloat(Temperatur2); // In my case: German locale!
    
    printf("%8.4f %8.4f\n", temp, temp2);
    

    The output is:

     12.4500  12.4500
    

    You can see that it works as expected. Note that on my system, the comma is the decimal separator for the locale, and yet this code works fine with the period as decimal separator, because of the invariant format settings.

    So make your choice: use TFormatSettings::Invariant() if you need independence of the locale, but don't use it if you want it to use the decimal separator for the locale of the user.