Search code examples
c#stringdecimalformatexception

C# string to decimal error


I'm having trouble with a very simple problem. Basically I'm taking a string, like "$30.00", and removing the '$' and then trying to convert it to a decimal. Although I keep getting an error stating that the string isn't in the correct format. Not sure what to do from here...

string freightstart = PostFregihtAmount.ToString();

freightstart = freightstart.TrimStart('$');

decimal freight = Decimal.Parse(freightstart);

I tried the following, per Alex Skiba's suggestion in the comments:

Decimal.Parse(freightstart, System.Globalization.CultureInfo.InvariantCulture);

This is the error I receive upon debugging:

enter image description here

This is a plugin for our onsite CRM 2011 system and some fields that I have to reference on the quote form are currency fields. When I query the data they come back as string formats, hence the example "$30.00". Long story short I need to convert it to decimal so that I may do my tax solution.


Solution

  • Try explicitly allowing the decimal point when you parse the string, as well as the currency symbol (then you don't have to trim the $ before parsing):

    var freight = Decimal.Parse("$30.00",
                  NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint);