I need to convert a string to a float. These is is my example string:
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 this is what i'm doing:
text = text.Substring(pos + 5, 9).Trim();
float val = 0.0F;
float.TryParse(texto, out val);
this.txtDimension1.Text = val.ToString();
Okay, this works for my environment, which is en_US, but when i run this same piece of code in an Spanish environment, it converts -00000.01 to -1.0
I think it's a comma problem, in english numbers are separated by a dot (".") and spanish they are separated by a comma (",").
How can i make this work on both langs?
Thanks, Richard.
You need to pass the CultureInfo for the culture that the strings are formatted in.
http://msdn.microsoft.com/en-us/library/3s27fasw.aspx
The example from MSDN would be:
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 then use CultureInfo.CurrentCulture
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With