2

How can I get the results to show each year and the year end value for each year?

double investment_decimal = Double.Parse(txtAmount.Text);
double rate_decimal = Double.Parse(txtRate.Text);
double years = Double.Parse(txtSlideValue.Text);
years = Convert.ToDouble(txtSlideValue.Text);
double calculation = 0;

        //for loop
            for (int i = 1; i < years + 1 ; i++)
            {

                calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
                txtCalculation.Text = Convert.ToString("Year " + i.ToString() +"\t" + "Year End Value " + calculation.ToString("C")).PadRight(10);
            }
1
  • 1
    Let's say that years is 5. You will go through that loop 5 times, and each time you will reset the value of calculation and txtCalculation to whatever it is on that iteration. If you want to output the values from each iteration, you either need to store the values in a variable collection (list, array, etc), or add the values onto the end of your variables (calculation = calculation + etc) Commented Mar 6, 2018 at 19:15

1 Answer 1

2

Your code makes multiple assignments to a UI element's text before letting UI refresh. That is why only the last item remains visible; the rest of them get overwritten as you go through the loop.

You should prepare a string that corresponds to the entire string in the text box, and put it into txtCalculation.Text all at once:

StringBuilder sb = new StringBuilder();
for (int i = 1; i < years + 1 ; i++)
{

    calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
    sb.AppendFormat("Year {0}\tYear End Value {1:C}\n", i, calculation);
}
txtCalculation.Text = sb.ToString();

Note the use of AppendFormat in place of string concatenation operator += with multiple values. If you want to make a string, rather than appending to StringBuffer, you could use string.Format or interpolated strings of C# 6.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.