?
Solved

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

Posted on 2010-08-23
10
Medium Priority
?
655 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
Technology Partners: 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

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