Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 669
  • Last Modified:

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

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
php-newbie
Asked:
php-newbie
2 Solutions
 
anarki_jimbelCommented:
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
 
RyanAndresCommented:
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
 
Carl TawnSystems and Integration DeveloperCommented:
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
anarki_jimbelCommented:
Just noticed: TryParse has return type boolean, not float - another mistake. I'm trying to write some code for you..
0
 
anarki_jimbelCommented:
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
 
Altin BardhiSoftware EngineerCommented:
Hi there,

You can try the following:

string str = "4.123";
float f = float.Parse(str);
0
 
anarki_jimbelCommented:
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
 
kris_perCommented:

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
 
Carl TawnSystems and Integration DeveloperCommented:
Erm, how is the accepted solution any different to the one I posted yesterday?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now