0

I'm trying to calculate the difference of sales and expenses from the database values that I have returned. But when I use a - b it throws the below error. Although I'm converting the double it still gives the error:

cannot implicitly convert type string to double

This is my code:

double a = Double.Parse(reader["sales"].ToString().Trim());
double b  = Double.Parse(reader["expenses"].ToString().Trim());

Label11.Text = a - b;

Any help will be appreciated.

2
  • When you debug, are a and b properly doubles? Have you tried doing Label11.Text = (a-b).ToString();? Commented Jul 8, 2013 at 17:33
  • both are returning double but adding that worked perfectly.. thanks Commented Jul 8, 2013 at 17:42

3 Answers 3

6

Because Text is of type string and the values obviously aren't (and therefore neither is the resulting value) of that type:

Label11.Text = (a - b).ToString();
Sign up to request clarification or add additional context in comments.

Comments

0

Unless you're sure that you're always going to have valid double values in the string then you might want to use TryParse instead in order to ensure no exceptions are thrown.

double a;
double b;

if (double.TryParse(reader["sales"].ToString().Trim(), out a))  
if (double.TryParse(reader["expenses"].ToString().Trim(), out b))        
    Label11.Text = (a - b).ToString(); //only called if both doubles were parsed

Comments

0

Instead of: Label11.Text = a - b;
use Label11.Text = (a - b).ToString();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.