Solved

How do I convert a string to a float? (C#)

Posted on 2010-08-23
10
641 Views
Last Modified: 2012-05-10
Hi Experts,

How do I convert a string to a float? (C#)

Something like this:

using namespace System;
using namespace System::Text;

int _tmain(int argc, _TCHAR* argv[])
{
  String ^ source_value = "195? mmmm";
  float f;
  f = float.TryParse(source_value, NumberStyles.Any, CultureInfo.InvariantCulture, out f);
  ...

  return 0;
}

I'm getting:
1>.\test1.cpp(20) : error C2062: type 'float' unexpected

Thanks!

0
Comment
Question by:php-newbie
10 Comments
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 33505706
Strange error you have. I believe it's a PHP error, not C# exception.

I believe to parse the string you need to extract numerical part of it. Parse method won't work with the string.

The error you have is because the string is not numeric.
0
 
LVL 8

Expert Comment

by:RyanAndres
ID: 33505720
Try either...
string sourceValue = "195? mmmm";
float converted = (float)Convert.ToDouble(sourceValue);

OR

double dblOut;
double.TryParse(sourceValue, out dblOut);
float converted = (float)dblOut;

Open in new window

0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 300 total points
ID: 33505780
I think the problem is that you are actually using C++/CLI rather than C#.

Try:
float f;

if (!float::TryParse(source_value, NumberStyles::Any, CultureInfo::InvariantCulture, f))

{

     // do something if conversion fails.

}

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 33505813
Just noticed: TryParse has return type boolean, not float - another mistake. I'm trying to write some code for you..
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 33506183
Consider thye following code:
        private void button2_Click(object sender, EventArgs e)

        {



                string  source_value = "195...0456? mmmm";

                string massagedSource = massageFloatSourceString(source_value);

                float f;

                bool canparse = float.TryParse(massagedSource, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out f);



                if (canparse)

                {

                    MessageBox.Show("f = " + f.ToString());

                }

                else

                {

                    MessageBox.Show("Can't convert the string");

                }



           



        }

        private string massageFloatSourceString(string source)

        {

            

            StringBuilder sb = new StringBuilder();

            foreach (char ch in source.ToCharArray())

            {

                if ((ch >= 48 && ch <= 57) || (ch == 46))

                {

                    sb.Append(ch);

                }

            }

            string output = sb.ToString().Trim( new char[]{' ', '.'});

            while(output.IndexOf("..")>-1){

                output = output.Replace("..", ".");

            }

            return output;

        }

Open in new window

0
 
LVL 8

Expert Comment

by:albacom
ID: 33507057
Hi there,

You can try the following:

string str = "4.123";
float f = float.Parse(str);
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 33507992
albacom, the asker gave his specific example - have a look. Second - It's a bad idea to use .Parse method. TryParse is much safer, anyone can tell. Especially in web applications where user (or someone else...) may post any rubbish...
0
 
LVL 16

Assisted Solution

by:kris_per
kris_per earned 200 total points
ID: 33509683

Your code is in managed c++.

The reason for the error 'type 'float' unexpected' is:
- enum values are accessed with ::  not with dot(.) So replace all your dots with :: in in the TryParse method.

Also remove "out" in the last param...

The fixed line is:

f = float::TryParse(source_value, NumberStyles::Any, CultureInfo::InvariantCulture, f);


using namespace System;

using namespace System::Globalization;



int main(array<System::String ^> ^args)

{

	String ^ source_value = "195? mmmm";

	float f;	

	

	f = float::TryParse(source_value, NumberStyles::Any, CultureInfo::InvariantCulture, f);



    Console::WriteLine(L"Hello World");

    return 0;

}

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 33511103
Erm, how is the accepted solution any different to the one I posted yesterday?
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Put text in a picture ASP.NET C# 2 36
Parse CSS value with RegEx 2 40
Build JSON from table records 17 40
Long URL in SMS 6 24
Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now