Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I convert a CString to a float??

Status
Not open for further replies.

Toe

Programmer
Oct 26, 2001
71
GB
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.
 
you can just do

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

Matt
 
What you did is absolutely valid and I use that all the time. 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();


HTH
Shyan
 
I am very glad you brought this up. When I write

CString string = "3.14";
float pi = 0.0f;
pi = atof(string);

I get the warning:

warning C4244: '=' : conversion from 'double' to 'float', possible loss of data

I have a project I am working on where I get this warning from this exact function atof() about 11 times. Strangly atof() returns a double, from MSDN

double atof( const char *string );

So my question is, should I go and change the doubles to floats, like I was planning, or doesn't it really matter? I don't like the warnings, and it really doesn't matter to me if I use a double or a float. A float is overkill already. (I'm storing dollar values).

Thanks guys
 
you can cast the return value to float:

pi = (float)atof(string);

This will get rid of the warnings.

If you are storing dollar values, you might want to stores cents instead, so that you can use int or long instead.

Vincent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top