简体   繁体   中英

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". How can I resolve this using 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. In France, decimal number are more written with a comma : 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:

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. 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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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