1. DBDev's Avatar
    Hi!

    Im pretty new to developing apps and i wonder why this code doesnt 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.
    02-13-2012 10:43 AM
  2. DanSmithKY's Avatar
    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.
    02-13-2012 11:40 AM
  3. gtg465x's Avatar
    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 by gtg465x; 02-13-2012 at 12:53 PM.
    02-13-2012 11:55 AM
  4. thed's Avatar
    Hi!

    Im pretty new to developing apps and i wonder why this code doesnt 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.
    DBDev and RogueCode like this.
    02-13-2012 11:57 AM
  5. JedH's Avatar
    What you should be using is the Int32.TryParse method.
    Int32.TryParse Method (String, Int32) (System)

    Realistically though looking at that math you should use doubles, then use the Double.TryParse method.
    02-13-2012 04:31 PM
  6. Jaer007ll's Avatar

    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.
    02-20-2012 06:22 PM

Tags for this Thread

LINK TO POST COPIED TO CLIPBOARD