Big Hendo
Big Hendo

Reputation: 185

Invalid input string when trying to perform a currency calculation

Hello I am getting an invalid input string in my code below and I am unsure how to fix it. What I am simply trying to do is calculate the base price and total discount. The output for the both is £...

For Example: Base Price £148.00 Discount £20

How do I fix the code below as I am using double.parse and Numberstyles:

    public double CalculateBasePriceAndTotalDiscountFromBasket(string basketLocation)
    {
        var basketSummaryContent = _driver.FindElements(CommonPageElements.BasketSummaryContent);
        var totalDiscountValue = _driver.FindElements(CommonPageElements.TotalDiscountValue);

        if (basketLocation.ToLower() == "top")
        {
            string basketSummaryContentText =
                basketSummaryContent[0].FindElement(CommonPageElements.BasePriceValue).Text;

            double basketSummaryPrice = double.Parse(basketSummaryContentText, NumberStyles.AllowCurrencySymbol);
            double totalDiscount = double.Parse(totalDiscountValue[0].Text, NumberStyles.AllowCurrencySymbol);

            return basketSummaryPrice - totalDiscount;
        }
        else
        {

            string basketSummaryContentText =
                basketSummaryContent[1].FindElement(CommonPageElements.BasePriceValue).Text;

            double basketSummaryPrice = double.Parse(basketSummaryContentText, NumberStyles.AllowCurrencySymbol);
            double totalDiscount = double.Parse(totalDiscountValue[1].Text, NumberStyles.AllowCurrencySymbol);

            return basketSummaryPrice - totalDiscount;
        }
    }

Upvotes: 1

Views: 80

Answers (2)

Steve
Steve

Reputation: 216313

Well, the error could only explained by a CultureInfo not valid for the pound currency symbol. You can force the correct culture on your parsing with

CultureInfo ci = new CultureInfo("en-GB");
double basketSummaryPrice = double.Parse(basketSummaryContentText, 
                            NumberStyles.Currency, ci);
double totalDiscount = double.Parse(totalDiscountValue[0].Text, 
                            NumberStyles.Currency, ci);

As already said in another answer I also recommend to use the decimal datatype when dealing with currency values. It will give exact results in mathematical operation on these values. Also note that in your context (you could have decimals on these numbers) it is better to use the NumberStyles.Currency to account also for the presence of decimal separator symbol.

Upvotes: 2

user8502296
user8502296

Reputation:

Try this instead of NumberStyles.AllowCurrencySymbol

double.Parse(value, NumberStyles.Currency); 

I would also recommend using decimal instead of double, since something like 0.01 really can't be accurately stored as a double.

Upvotes: 0

Related Questions