0

My application suddenly started failing to convert a string value of format "18.000" to a decimal or int with the error

System.FormatException: Input string was not in a correct format.

When trying either

decimal.Parse(stringValue);
int.Parse(stringValue);    

Even though a couple of days earlier this was working fine. It also worked on my local machine but not on the publishing server.

It turns out I could resolve this by passing in CultureInfo.InvariantCulture like this:

decimal.Parse(aod.PnPQuantity, CultureInfo.InvariantCulture)

But when I check the server's localisation settings, it definitely uses a . as a decimal seperator:

enter image description here

My question is, how is this possible? Is there some other setting I need to check, and is this something that could have changed on its own or has someone been messing with my settings?

Will passing in InvariantCulture as I have prevent this from happening in the future, or do I need to take further precautions?

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • Where is the string coming from? – Zohar Peled Oct 10 '18 at 07:18
  • @ZoharPeled The string is sent through as an element in a larger soap message, which I recieve, process and insert into an ms-access db – Bassie Oct 10 '18 at 07:20
  • This might help you understand what is needed/recommended in number formatting: https://stackoverflow.com/questions/5060446/difference-between-currentculture-invariantculture-currentuiculture-and-instal – LocEngineer Oct 10 '18 at 08:06
  • What I means is are you sure the string should always be well-formatted, or is it coming from a source you don't control such as a 3rd party of user input. Because if it's the second option, you should prefer `TryParse` over `Parse`. – Zohar Peled Oct 10 '18 at 08:40
  • @ZoharPeled The string comes from a 3rd party, and yes I should be using `TryParse`, but that is not what is causing the issue as I have verified several inputs myself and the issue still occurs – Bassie Oct 10 '18 at 09:04
  • Ok, so yes, to answer your question, sending `InvariantCulture` to the `Parse` method will cause it to try and parse the input string according to the `InvariantCulture` rules, not the local settings of the OS the application is running on. – Zohar Peled Oct 10 '18 at 09:54
  • @ZoharPeled But the question is, why does `Parse` (without `InvariantCulture`) fail to do the conversion when the OS settings looks correct – Bassie Oct 10 '18 at 10:01
  • If I would have known that, I would have posted an answer, not a comment... – Zohar Peled Oct 10 '18 at 10:02
  • @ZoharPeled You said "to answer your question" - which question were you answering exactly? – Bassie Oct 10 '18 at 10:02
  • The last one: "Will passing in InvariantCulture as I have prevent this from happening in the future, or do I need to take further precautions?" It's not my fault your post contains multiple questions :-) – Zohar Peled Oct 10 '18 at 10:32

0 Answers0