Why doesn?t this work?

DBDev

New member
Jan 13, 2012
2,380
0
0
Hi!

I?m pretty new to developing apps and i wonder why this code doesn?t work?

int dataUsed = int.Parse(dataPerMonthTextBox.Text) - int.Parse(dataLeftTextBox.Text);
int procentUsed = dataUsed / int.Parse(dataPerMonthTextBox.Text);

procentUsedTextBlock.Text = "Procent used: " + procentUsed;

In the textblock i get "Procent used: 0" no matter wath i write in the textblocks and when i debug the application i se that the both the integers are 0.
 
I'm not in a location to try this out, but if you put a .toInt() after the .Text of your boxes, will it work? Or perhaps you have to put the .Text values in string variables first, and then toInt() the strings.
 
Does this work?

int dataUsed = Convert.ToInt(dataPerMonthTextBox.Text) - Convert.ToInt(dataLeftTextBox.Text);
float procentUsed = ((float)dataUsed / Convert.ToInt(dataPerMonthTextBox.Text)) * 100;

procentUsedTextBlock.Text = "Procent used: " + procentUsed.ToString();
 
Last edited:
Hi!

I?m pretty new to developing apps and i wonder why this code doesn?t work?

int dataUsed = int.Parse(dataPerMonthTextBox.Text) - int.Parse(dataLeftTextBox.Text);
int procentUsed = dataUsed / int.Parse(dataPerMonthTextBox.Text);

procentUsedTextBlock.Text = "Procent used: " + procentUsed;

In the textblock i get "Procent used: 0" no matter wath i write in the textblocks and when i debug the application i se that the both the integers are 0.

There are 2 problems here. First, you're using integer math. If you divide an int by an int, the result will always come back as an int. For example, if you divide 1/2, the "real" answer is 0.5, but that gets casted to an int, which causes it to lose the decimal place, so you end up with 0. But if either the dividend or divisor is a float then floating point math will be used. Try casting one of the ints to a float like this:
(float)dataUsed / int.Parse(dataPerMonthTextBox.Text)

The second problem is that you're using an int to store the result. As I mentioned above, the int type does not store decimal places. Try changing the procentUsed variable to a float instead.
 
avatar1.jpg

I'm not in a location to try this out, but if you put a .toInt() after the .Text of your boxes, will it work? Or perhaps you have to put the .Text values in string variables first, and then toInt() the strings.
 

Members online

No members online now.

Forum statistics

Threads
339,522
Messages
2,262,548
Members
428,762
Latest member
Garciabettys