Convert CString to float in mfc

26,257

you can just do

    CString pi = "3.14";
    return atof(pi);

EDIT

Also use this function:

    CString pi = "3.14";
    return _ttof(pi);

Reading a string value and parse/convert it to float allows you to locate the error when there is one. All you need is a help of a C Run-time function: strtod() or atof().

I would prefer strtod as the second argument returns a pointer to the string where the parse terminated:

 CString str;
m_edtMyEditBox.GetWindowText(str);
char *pEnd;
double dValue = strtod(str.GetBuffer(str.GetLength()), &pEnd);
if (*pEnd != '\0')
{
    // Error in parsing
}
str.ReleaseBuffer();
Share:
26,257
karthik
Author by

karthik

.NET Developer having experience in MVC, Web Development, WCF Services.

Updated on July 25, 2022

Comments

  • karthik
    karthik almost 2 years

    how can I convert a CString variable to a floating point? (I'm using visuall c++ 6.0 and the MFC)

    I'm trying to use an edit box to return a value which I'm putting into an array of floating points. I'm Using the GetWindowText method to get the value, which returns a CString. So I need to convert to a floating point. (or am I just doing things completely the wrong way?).

    I presume there are methods for doing this already in the MFC.(have already used the Format method to convet to a CString display the values in the array in the edit box)

    Thanks.

  • MikMik
    MikMik about 13 years
    I think it should be CString pi = _T("3.14"); if he's going to use _ttof()
  • karthik
    karthik about 13 years
    @MikMik: if the application supports unicode characters then you should use _T() Macro otherwise no need of that macro.
  • MikMik
    MikMik about 13 years
    First, it's 2011. Apps should support Unicode. And second, if the app supports Unicode you should use L"String" and _wtof. If it doesn't, "String" and atof. _T("String") and _ttof are generic versions which map to the correct one according to the project settings. But mixing "String" and _ttof is mixing an ANSI literal with a generic function, which accidentally works in a non-unicode build, but is wrong.