none
Input string was not in a correct format error when trying to parse British Pound RRS feed

  • Question

  • I am trying to parse an amount field that can be either in US Dollars or British Pounds.  The following line of code works just fine with the US Dollar, however, as soon as the Pound comes in, it throws an exception stating the Input string was not in a correct format. Here is the line of code:

    Works

    bool validAmount;
    validAmount = (decimal.Parse("$2.00", NumberStyles.Currency) != 0);

    Doesn't work

    bool validAmount;
    this.validAmount = (decimal.Parse("£2.00", NumberStyles.Currency) != 0);

     

    Does anyone know why this might be?


    Thanks!

    Flea

    Tuesday, May 11, 2010 8:50 PM

Answers

  • Try:

     

     

    CultureInfo jojo = new CultureInfo("en-GB",false);

     

    decimal d = decimal.Parse("£2.00", NumberStyles.Currency, jojo);

     

     

     

     

     

    Vanderghast, Access MVP

     

    • Proposed as answer by Vanderghast Tuesday, May 11, 2010 10:08 PM
    • Marked as answer by Flea_ Wednesday, May 12, 2010 7:50 PM
    Tuesday, May 11, 2010 10:08 PM

All replies

  • $2.00 is valid under en-us culture. £2.00 is valid under en-gb culture. You need to specify the culture of the string you want to parse:

    If you don't know in advance which culture you need, test the presence of the $ or £ character.

    The following method checks if the string contains a valid non-zero amount in dollars or pounds:

    public bool IsAmountValid(string amount)
    {
      CultureInfo culture;
      if (amount.Contains("$"))
        culture = new CultureInfo("en-us");
      else
        culture = new CultureInfo("en-gb");
    
      decimal result;
      return decimal.TryParse(amount, NumberStyles.AllowCurrencySymbol, culture, out result)
        && result != 0;
    }
    • Proposed as answer by Vanderghast Tuesday, May 11, 2010 10:15 PM
    Tuesday, May 11, 2010 9:44 PM
  • Try:

     

     

    CultureInfo jojo = new CultureInfo("en-GB",false);

     

    decimal d = decimal.Parse("£2.00", NumberStyles.Currency, jojo);

     

     

     

     

     

    Vanderghast, Access MVP

     

    • Proposed as answer by Vanderghast Tuesday, May 11, 2010 10:08 PM
    • Marked as answer by Flea_ Wednesday, May 12, 2010 7:50 PM
    Tuesday, May 11, 2010 10:08 PM