-2

I have some code that divides the number of elements in a collection by one hundred. But in the end it shows the wrong value.

private void FillPages()
        {
            double numofpages = listcoinslist.Count / 100;
            MessageBox.Show(listcoinslist.Count + " " + numofpages);
        }

The picture of the calculation result

I should get 65.6, instead I get 65. The same number is displayed on the label. This is not a display error, but a strange calculus error.

  • 2
    `.Count` is an `int`, `100` is an `int`. `int / int` is an `int`. Assigning an `int` to a `double` does not change that. – crashmstr Mar 29 '21 at 12:56
  • 2
    Use `/ 100.0` and try again – Hoang Mar 29 '21 at 12:57
  • 1
    Might be a better duplicate, but related: [Why does integer division in C# return an integer and not a float?](https://stackoverflow.com/q/10851273/1441) – crashmstr Mar 29 '21 at 12:59

2 Answers2

1

This is due to rounding to int values because both values seem to be ints. Make sure you have at least one decimal number.

Make sure you devide with a float or double by adding .0, for example:

double numofpages = listcoinslist.Count / 100.0;

Waescher
  • 5,361
  • 3
  • 34
  • 51
0
double numofpages = (double)listcoinslist.Count / 100;

The problem was that you need to specify the number of elements in the collection as double.