1

Sorry if this question has already been asked I just can't find how to do it in my problem. I imported a file with a list of numbers from 1-20 into a listbox and then displayed the total amount of values and average into textboxes. I'm getting the right calculations it's just I have no clue how to convert them.

My code is:

int i = 0;
int result = 0;
while (i < lstbxDisplayInfo.Items.Count)
{
   result += Convert.ToInt32(lstbxDisplayInfo.Items[i++]);
}
//Displays average.
txtAverage.Text = Convert.ToString((double)result / i);
//Displays Amount.
txtAmount.Text = Convert.ToString((double) i);

my output is:

Average: 10.5
Total Amount: 20

I need the output to be:

Average: 10.50
Total Amount: 20.00
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user3041721
  • 13
  • 2
  • 4

2 Answers2

6

You can use .ToString() method with #.00 format like;

(10.5).ToString("#.00");
(20).ToString("#.00");

Output will be;

10.50
20.00

Here a demonstration.

The "#" custom format specifier serves as a digit-placeholder symbol. If the value that is being formatted has a digit in the position where the "#" symbol appears in the format string, that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string.

EDIT: Of course # doesn't represents zeros, that's why you should use #.00 instead of #.## format.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

If you need two decimal places i would use decimal instead. Two display them you can use d.ToString("N2"). Here is a more concise LINQ approach:

var allNums = lstbxDisplayInfo.Items.Cast<object>()
    .Select(o => decimal.Parse(o.ToString()));
decimal average = allNums.Average();
decimal total = allNums.Sum();
Console.WriteLine(average.ToString("N2"));
Console.WriteLine(total.ToString("N2"));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939