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?

3
  • what is your current culture? Commented Apr 17, 2013 at 13:42
  • I hope it helps stackoverflow.com/questions/5365566/… Commented Apr 17, 2013 at 13:43
  • @Tonix Because probably you are not use the same Culture with Barbara. Commented Apr 17, 2013 at 13:46

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

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 :

Comments

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.

Comments

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

Comments

0

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

MessageBox.Show(yeahFloat.ToString("0.0")); // 1 decimal place

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.