Link to home
Start Free TrialLog in
Avatar of Jax Logan
Jax Logan

asked on

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!

Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

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.
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

ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just noticed: TryParse has return type boolean, not float - another mistake. I'm trying to write some code for you..
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

Hi there,

You can try the following:

string str = "4.123";
float f = float.Parse(str);
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...
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Erm, how is the accepted solution any different to the one I posted yesterday?