ric*_*rto 5 c# floating-point locale
我需要将字符串转换为float.这是我的示例字符串:
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
这就是我正在做的事情:
text = text.Substring(pos + 5, 9).Trim();
float val = 0.0F;
float.TryParse(texto, out val);
this.txtDimension1.Text = val.ToString();
Run Code Online (Sandbox Code Playgroud)
好的,这适用于我的环境,即en_US,但是当我在西班牙语环境中运行同一段代码时,它会将-00000.01转换为-1.0
我认为这是一个逗号问题,英文数字用点(".")和西班牙语分隔,用逗号(",")分隔.
我怎样才能在这两个语言上做这个工作?
谢谢,理查德.
您需要传递CultureInfo以获取格式化字符串的文化.
http://msdn.microsoft.com/en-us/library/3s27fasw.aspx
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);
Run Code Online (Sandbox Code Playgroud)
或者,如果输入字符串的格式不同,则使用CultureInfo.CurrentCulture