(Picture is attached for reference) I need to have "Year x:" followed by the calculation in a list box. I can get the calculations (incorrectly so far), but I'm not sure how to add the "Year x" part before each calculation.
Any help is appreciated. TIA!
Here is my code for the button click event:
private void btnCalculate_Click(object sender, System.EventArgs e) { try {
if (DataIsValid())
{
// Change to Parse methods that check for formatting characters
decimal monthlyInvestment =
Decimal.Parse(txtMonthlyInvestment.Text, NumberStyles.Currency);
decimal interestRateYearly =
Decimal.Parse(txtInterestRate.Text, NumberStyles.Number);
int years =
Int32.Parse(comboNumberOfYears.Text, NumberStyles.Number);
int months = years * 12;
decimal interestRateMonthly = interestRateYearly / 12 / 100;
decimal futureValue = CalculateFutureValue(
monthlyInvestment, interestRateMonthly, months);
// Add statements that format the values that are displayed
// Monthly investment
txtMonthlyInvestment.Text = monthlyInvestment.ToString("c");
// Yearly interest rate
txtInterestRate.Text = (interestRateYearly / 100).ToString("p2");
// Future value
listFutureValue.Items.Clear();
for (int i = 1; i <= years; i )
{
futureValue /= i;
listFutureValue.Items.Add(futureValue.ToString("c"));
}
txtMonthlyInvestment.Focus();
}
}
CodePudding user response:
There are various options but they are all variations of the same thing. You just need to create a string that contains the literal part and the rest. The obvious option should have been this:
listFutureValue.Items.Add("Year " i ": " futureValue.ToString("c"));
I'm not sure how you could not know that that was possible. That said, the better option would be this:
listFutureValue.Items.Add($"Year {i}: {futureValue:c}");
That's using string interpolation, which is basically direct language support for the String.Format
method. You should read the documentation for that method and string interpolation for more information.