Vadzim Savenok Vadzim Savenok - 2 months ago 5
C# Question

Format() number string with comma while it is converted to string inside for loop

I already know HOW to format number string with comma like I need from this thread, in fact, I am trying to apply the accepted answer to my case.

However, from what I see, it deals with predetermined string variable. In my case, it is running a for-loop, which converts a double value to string and displays output as table rows.

for (double i = 1; i <= years; i++)
//number of years //future value
richTextBoxResults.Text += i.ToString().PadLeft(3) + (presentValue * Math.Pow(((interestRate / 100 / periods) + 1), (periods * i))).ToString("$#.00").PadLeft(28) + "\n";

To keep things simple, 3 output rows should be sufficient to get the idea

Years Future Value
1 $1234567.89
2 $2345678.90
3 $3456789.01

I tried to use Format() inside the loop after the .ToString("$#.00") method, however, I was getting an error of Method() cannot be accessed _with an instance reference. However, I am not sure how I can apply those answers to my case.

I was thinking about creating a string variable, which would temporarily store values and format it. But I am wondering if there is a more elegant solution.

Can I still apply Format() method (maybe under the different angle), so my output would be like the following

Years Future Value
1 $1,234,567.89
2 $2,345,678.90
3 $3,456,789.01

Or to I need to change my approach to that?


Your code is not readable which is making it hard for you to understand the problem. You have an extra ) before the .ToString :

Math.Pow(((interestRate / 100 / periods) + 1), (periods * i)).ToString("$#.00").PadLeft(28)

You can use "$0,#.00" to apply a thousands separator.