Solved

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

Posted on 2010-08-23
10
645 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What's the most efficient way to load up a couple of large table in C#? 5 45
Error in script 11 56
C# Desktop Application 3 32
HttpPostedFile 1 26
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.

770 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