0

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?

Barbara PM
  • 512
  • 2
  • 8
  • 29

5 Answers5

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

See documentation: http://msdn.microsoft.com/en-us/library/bh4863by.aspx

tnw
  • 13,521
  • 15
  • 70
  • 111
3

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 :

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
1

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.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
1

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());    
   }
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
0

Try passing the formatting you require in the ToString() method

MessageBox.Show(yeahFloat.ToString("0.0")); // 1 decimal place
MattP
  • 2,798
  • 2
  • 31
  • 42