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_valu e, NumberStyles.Any, CultureInfo.InvariantCultu re, out f);
...
return 0;
}
I'm getting:
1>.\test1.cpp(20) : error C2062: type 'float' unexpected
Thanks!
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_valu
...
return 0;
}
I'm getting:
1>.\test1.cpp(20) : error C2062: type 'float' unexpected
Thanks!
Try either...
string sourceValue = "195? mmmm";
float converted = (float)Convert.ToDouble(sourceValue);
OR
double dblOut;
double.TryParse(sourceValue, out dblOut);
float converted = (float)dblOut;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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;
}
Hi there,
You can try the following:
string str = "4.123";
float f = float.Parse(str);
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Erm, how is the accepted solution any different to the one I posted yesterday?
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.