C # String to Float Conversion

I need to convert a string to float. This is my sample line:

1 MW +00000.00 mm
2 MW +0000.000 mm
3 MW -00000.01 mm
4 MW +00000.00 mm
5 MW +00002.92 mm
6 MW +00002.69 mm

And here is what I do:

text = text.Substring(pos + 5, 9).Trim(); float val = 0.0F; float.TryParse(texto, out val); this.txtDimension1.Text = val.ToString(); 

Ok, this works for my environment, which is en_US, but when I run the same piece of code in the Spanish environment, it converts -00000.01 to -1.0

I think this is a comma problem, in English the numbers are separated by a period (".") And Spanish, they are separated by a comma (",").

How can I do this job in both languages?

Thanks Richard.

+4
source share
5 answers

You need to pass CultureInfo for the culture into which the rows are inserted.

http://msdn.microsoft.com/en-us/library/3s27fasw.aspx

Example from MSDN:

 double number; string value = "1,097.63"; NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol; CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); if (Double.TryParse(value, style, culture, out number)) Console.WriteLine("Converted '{0}' to {1}.", value, number); else Console.WriteLine("Unable to convert '{0}'.", value); 

Alternatively, if your input strings are formatted differently, use CultureInfo.CurrentCulture

+5
source

Use CultureInfo.InvariantCulture.

 float.TryParse(texto, NumberStyles.Any, CultureInfo.InvariantCulture, out val); 

If the input lines may vary, you will have to discover this and match your input with the right culture.

+4
source

You can try to implement using the ToSingle method, which is essentially an alias of "Float"

in c #.

 float val = (float)System.Convert.ToSingle(text); 

I agree with Robert Harvey when he provides cultural information and uses Tryparse overload. Good suggestion!

+2
source

This is not an answer to the question, but I added it as an answer to show the code.

I just want to warn you about using Substring . This can cause a problem when the first number becomes greater than 9 [Two characters +].

I think in this case it is better to use a regular expression, and this is the expression you need:

 string str = @"4 MW +12345.67 mm"; Regex r = new Regex(@".* MW (?<number>.+) mm", RegexOptions.IgnoreCase); var match = r.Match(str); string matchedString = string.Empty; if (match.Success) matchedString = match.Groups["number"].Value; Console.WriteLine(matchedString); 

Note: you can improve the quality of the expression by checking the value if it is a stream number, but I think this is enough for your situation.

Good luck

+1
source

You will need to use TryParse overload, which allows you to specify Culture, you want to get culture information for en-us, and then you can parse it for everyone.

0
source

All Articles