none
Converting string to float RRS feed

  • Question

  • Hi

    I'm having trouble converting a string (as in String^) to a float value. The number will always be in the form ##.##

    The string is a substring of 2 numbers... see code...
    ...
    String^ setFreq = fullCommand->Substring(1,5); this->serAddr2->Text = setFreq; float initVal; Single::TryParse(setFreq, initVal); array<unsigned char>^ txBCD = {0xA9,0x00,0x00,0xDF,0x00,0x00,0x00,0x00,0x00}; int BCDInt = convertFreq(initVal); txBCD[6] = (char)(BCDInt >> 8); txBCD[7] = (char)(BCDInt & 0xFF); txBCD[8] = txBCD[0]+txBCD[1]+txBCD[2]+txBCD[3]+txBCD[4]+txBCD[5]+txBCD[6]+txBCD[7]; this->inverterComm->Write(txBCD,0,9); int setTimer = int::Parse(fullCommand->Substring(7));
    ...


    I need initVal to be a float to pass to a function that encodes the value into the right format for a serial protocol.

    I've tried the following...
    initVal = System::Convert::ToSingle(setFreq);
    
    float::Parse(setFreq, initVal);
    
    Single::Parse(setFreq, initVal);
    All results are zero. I think that it may be my syntax but I don't know where.

    Any help is appreciated, this is basically the final hurdle to finishing my program.
    Wednesday, July 15, 2009 1:07 AM

Answers

  • Parse() and TryParse() will use the machine's default culture to try to parse the value.  That won't work with the given string (##.##) if the current culture uses something else than a period for the decimal point.  A comma is very common in Europe for example.  Use the Try/Parse() overload that accepts the IFormatProvider argument and pass the invariant culture:

          String^ test = "12.34";
          float value;
          bool ok = float::TryParse(test,
            System::Globalization::NumberStyles::AllowDecimalPoint,
            System::Globalization::CultureInfo::InvariantCulture->NumberFormat,
            value);


    Hans Passant.
    Wednesday, July 15, 2009 11:39 AM
    Moderator

All replies

  • Parse() and TryParse() will use the machine's default culture to try to parse the value.  That won't work with the given string (##.##) if the current culture uses something else than a period for the decimal point.  A comma is very common in Europe for example.  Use the Try/Parse() overload that accepts the IFormatProvider argument and pass the invariant culture:

          String^ test = "12.34";
          float value;
          bool ok = float::TryParse(test,
            System::Globalization::NumberStyles::AllowDecimalPoint,
            System::Globalization::CultureInfo::InvariantCulture->NumberFormat,
            value);


    Hans Passant.
    Wednesday, July 15, 2009 11:39 AM
    Moderator
  • Thanks

    Everything works good now
    Tuesday, July 21, 2009 3:14 AM