Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2010-08-23
10
Medium Priority
?
661 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 30

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 1200 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

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 30

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 30

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

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.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

597 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