C#字符串到浮点转换 [英] C# String to Float Conversion

查看:139
本文介绍了C#字符串到浮点转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个字符串转换为一个浮点数。这是我的例子字符串:

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();

好的,这适用于我的环境,即en_US,但是当我运行同一段代码在西班牙语环境中,它将-00000.01转换为-1.0。我认为这是一个逗号问题,英文数字之间用点分隔(。)和西班牙语

我怎样才能使这两个langs工作?



感谢,
Richard。

解决方案

您需要传递文化格式的CultureInfo。

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



MSDN的例子是:

 双数; 

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(无法转换{0},value);

另外,如果您的输入字符串的格式不同,请使用 CultureInfo.CurrentCulture


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

这篇关于C#字符串到浮点转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆