简体   繁体   English

如何在C#中从String解析为Float?

[英]How to parse from String to Float in C#?

This issue should be very simple but I can't find the way to make it work. 这个问题应该很简单,但是我找不到使其工作的方法。 I have the following code: 我有以下代码:

string yeah = "0.5";
float yeahFloat = float.Parse(yeah);
MessageBox.Show(yeahFloat.ToString());

But the MessageBox shows "5" instead of "0.5". 但是消息框显示为“ 5”而不是“ 0.5”。 How can I resolve this using float? 如何使用float解决此问题?

float yeahFloat = float.Parse(yeah, CultureInfo.InvariantCulture);

请参阅文档: http : //msdn.microsoft.com/en-us/library/bh4863by.aspx

0.5 is the way some country are writing decimal number, like in America. 0.5是某些国家/地区写小数的方式,例如在美国。 In France, decimal number are more written with a comma : 0,5 . 在法国,小数点后更多用逗号写: 0,5
Typically, the code you give throw an exception on my computer. 通常,您提供的代码会在我的计算机上引发异常。

You need to specify from what culture you are expected the string to be parse. 您需要指定您希望从哪种文化中解析字符串。 If not, it will take your computer culture setting, which is bad, since your code could run in different countries. 如果不是这样,将需要您的计算机区域性设置,这很糟糕,因为您的代码可以在不同的国家/地区运行。

So, by specifying an invariant culture, you said to the Parse function : ok, let's try to parse point or comma, try as hard as you can: 因此,通过指定不变的区域性,您对Parse函数说了:好的,让我们尝试解析点或逗号,并尽最大努力:

string yeah = "0.5";
float yeahFloat = float.Parse(yeah, CultureInfo.InvariantCulture);
Console.Write(yeahFloat);

There is a lot of question already on this subject : 关于这个问题已经有很多问题了:

By default, Single.Parse(String) parses based on your localization settings. 默认情况下, Single.Parse(String)根据您的本地化设置进行解析。 If you want to use a specific one, you'll have to use an appropriate overload of that method with the culture settings that you want. 如果要使用特定的方法,则必须使用该方法的适当重载以及所需的区域性设置。

You can try this with float.TryParse() : 您可以使用float.TryParse()进行尝试:

string yeah = "0.5";
float yeahFloat;
 if (float.TryParse(yeah,System.Globalization.NumberStyles.Any,
     System.Globalization.CultureInfo.InvariantCulture,out yeahFloat))
   {
     MessageBox.Show(yeahFloat.ToString());    
   }

尝试在ToString()方法中传递所需的格式

MessageBox.Show(yeahFloat.ToString("0.0")); // 1 decimal place
 String yeah = "0.5";
float yeahFloat = Convert.ToSingle(yeah);
MessageBox.Show(yeahFloat.ToString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM