2

Here is basically the code I have :

string text = "-0.05537987";

float value = Single.Parse(text);

When I try and parse a negative number like I did here I get "Input string was not in the correct format."

redonkulasman
  • 45
  • 2
  • 11

3 Answers3

7

Your parsing should work, I believe your current culture has a different character for decimal separator. Use CultureInfo.InvariantCulture

float value = Single.Parse(text, CultureInfo.InvariantCulture);
Habib
  • 219,104
  • 29
  • 407
  • 436
  • Or he could change his thread culture to appropriate culture... Thread.CurrentThread.CurrentCulture = new CultureInfo("his-string-format-culture"); – HABJAN Jun 17 '14 at 13:24
  • @user3740638, are you sure the value you have in text is `"-0.05537987"` ? it should work. – Habib Jun 17 '14 at 13:33
  • Ummmmmmmm im an idiot. In my actual code i was splitting the string using dashes and the dash for the negative split the string and messed everything up. Sorry and Thanks for the quick responses. – redonkulasman Jun 17 '14 at 13:36
4

Your code works fine for me - https://dotnetfiddle.net/JfPfss

Use InvariantCulture and see if that is the issue:

float value = Single.Parse(text, CultureInfo.InvariantCulture);
manojlds
  • 290,304
  • 63
  • 469
  • 417
0

Just use CultureInfo.InvariantCulture

string text = "-0.05537987";
float value = Single.Parse(text, CultureInfo.InvariantCulture);
MessageBox.Show("your value = "+value);
MRebai
  • 5,344
  • 3
  • 33
  • 52